【问题标题】:Fastest way to merge and append multiple CSVs / data frames using pandas使用 pandas 合并和附加多个 CSV/数据帧的最快方法
【发布时间】:2021-03-22 14:56:05
【问题描述】:
我有以下数据框/CSV:
df1=
Person apple ball
A 3 4
B 5 1
df2=
Person apple cat
A 3 6
B 5 2
df3=
Person apple cat
C 6 2
D 2 2
df4=
Person dog cat
C 1 2
D 1 2
我有兴趣了解合并和附加此类数据帧的最快方法
'人'。预期的输出如下所示:
output=
Person apple ball cat dog
A 3 4 6 nan
B 5 1 2 nan
C 6 nan 2 1
D 2 nan 2 1
【问题讨论】:
标签:
python
pandas
dataframe
【解决方案1】:
如果同一列和索引的值在所有DataFrames 中都相同,则可以使用:
这意味着例如对于index=A,column=apple 是每个 Dataframe 相同的值 - 这里是 3(如果存在)
dfs = [df1, df2, df3, df4]
#if Person is column, not index
dfs = [x.set_index('Person') for x in dfs]
df = pd.concat(dfs).groupby(level=0).first()
print (df)
apple ball cat dog
Person
A 3.0 4.0 6.0 NaN
B 5.0 1.0 2.0 NaN
C 6.0 NaN 2.0 1.0
D 2.0 NaN 2.0 1.0
【解决方案2】:
看看这是否适合你的用例,合并在列和索引标签上,最后连接结果:
first = df1.merge(df2, on=["index", "apple"])
second = df3.merge(df4, on=["index", "cat"])
pd.concat([first, second])
apple ball cat dog
index
A 3 4 6 3
B 5 1 2 8
C 6 8 2 1
D 2 3 2 1