DF1: ID Nama 101 Rick 102 Nick 103 Jerry DF2: ID Kelas 101 A 102 B 103 C DF3: ID Kelas 101 1 102 2 103 3 Saya perlu menggabungkan beberapa data melalui loop. Saya mencoba: data_frame = ...

2
denz franc 5 April 2021, 21:10

4 jawaban

Jawaban Terbaik
#Import pandas
import pandas as pd


df1 = [[101, "Rick"],[102, "Nick"],[103, "Jerry"]]

df2 = [[101, "A"],[102, "B"],[103, "C"]]

df3 = [[101, 1],[102, 2],[103, 3]]

df1 = pd.DataFrame(df1, columns=["Id","Name"])
df2 = pd.DataFrame(df2, columns=["Id","Class"])
df3 = pd.DataFrame(df3, columns=["Id","Grade"])

df_final_mode1 = df1.merge(df2, left_on='Id', right_on='Id')
df_final_mode1 = df_final_mode1.merge(df3, left_on='Id', right_on='Id')

print('=== mode 1 - Merge ===')
print(df_final_mode1)

print()

print('=== mode 2 - Loop ===')
df_final_mode2 = df1

for index, (id, name) in df2.iterrows():
    df_final_mode2.loc[df_final_mode2.Id == id, 'Class'] = df2.loc[df_final_mode2.Id == id, 'Class']

for index, (id, name) in df3.iterrows():
    df_final_mode2.loc[df_final_mode2.Id == id, 'Grade'] = df3.loc[df_final_mode2.Id == id, 'Grade']

print(df_final_mode2)

enter image description here

0
Gilmar Vaz 5 April 2021, 18:36

Gunakan df.merge :

In [1389]: df1.merge(df2).merge(df3)
Out[1389]: 
    Id   Name Class  Grade
0  101   Rick     A      1
1  102   Nick     B      2
2  103  Jerry     C      3

atau gunakan df.join:

In [1393]: df1.set_index('Id').join(df2.set_index('Id')).join(df3.set_index('Id'))
Out[1393]: 
      Name Class  Grade
Id                     
101   Rick     A      1
102   Nick     B      2
103  Jerry     C      3

atau gunakan pd.concat :

In [1395]: pd.concat([df1.set_index('Id'), df2.set_index('Id'), df3.set_index('Id')], 1)
Out[1395]: 
      Name Class  Grade
Id                     
101   Rick     A      1
102   Nick     B      2
103  Jerry     C      3
0
Mayank Porwal 5 April 2021, 18:17

Anda dapat menggunakan concat untuk menggabungkan beberapa bingkai data pada indeks mereka.

data_frames = [df1, df2, df3]

# if "Id" is not already the index on these dataframes
data_frames [d.set_index("Id") for d in data_frames]
out = pd.concat(data_frames, axis=1)

print(out)
      Name Class  Grade
Id
101   Rick     A      1
102   Nick     B      2
103  Jerry     C      3
0
Cameron Riddell 5 April 2021, 18:17

Di jalan adalah dengan menggunakan functools.reduce:

from functools import reduce

reduce(lambda x,y: x.merge(y,on='Id', how='left'), dataframes )

Keluaran:

    Id   Name Class  Grade
0  101   Rick     A      1
1  102   Nick     B      2
2  103  Jerry     C      3
1
Quang Hoang 5 April 2021, 18:13