【问题标题】:Fastest way to merge Dataframe into one data frame将数据框合并到一个数据框的最快方法
【发布时间】:2020-06-04 05:35:12
【问题描述】:

我想尽快将两个 Dataframe 合并为 1 个。

DF1:

    A   B   C
0  A0  B0  C0
1  A1  B1  C1
2  A2  B2  C2
3  A3  B3  C3
4  A4  B4  C4
5  A5  B5  C5
6  A6  B6  C6
7  A7  B7  C7

</pre>

DF2:

AZ 0 A3 Z4 1 A5 Z5 2 A6 Z6 3 A7 Z7

当前结果:

A B C Z 0 A0 B0 C0 南 1 A1 B1 C1 南 2 A2 B2 C2 南 3 A3 B3 C3 [Z4] 4 A4 B4 C4 [Z4] 5 A5 B5 C5 [Z5] 6 A6 B6 C6 [Z6] 7 A7 B7 C7 [Z7]

要求的结果:

A B C Z 0 A0 B0 C0 南 1 A1 B1 C1 南 2 A2 B2 C2 南 3 A3 B3 C3 Z4 4 A4 B4 C4 南 5 A5 B5 C5 Z5 6 A6 B6 C6 Z6 7 A7 B7 C7 Z7

我的代码存在三个问题。 1)我不希望 Z4 重复。如果它为空,我只想要 NaN。
2) 我不知道为什么,但它应该是字符串格式时作为列表出现。
3) 非常慢。

注意:DF2 数据框 A 列中的所有内容将始终位于 D2 A 列中
我当前的代码

```
import pandas as pd
df1 = pd.DataFrame({'A': ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7'],
'B': ['B0', 'B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7'],
'C': ['C0', 'C1', 'C2', 'C3','C4', 'C5', 'C6', 'C7']},
index=[0, 1, 2, 3, 4, 5, 6, 7])

df2 = pd.DataFrame({'A': ['A3', 'A5', 'A6', 'A7'],
'Z': ['Z4', 'Z5', 'Z6', 'Z7'],
},
index=[0, 1, 2, 3])

def mergeDF(df1, df2):
   import pandas as pd
   v = df1.merge(df2[['A', 'Z']])\
      .groupby(df1.columns.tolist())\
      .Z\
      .apply(pd.Series.tolist)

   df = pd.DataFrame(v.tolist(), index=v.index)\
      .rename(columns=lambda x: x + 1)\
      .add_prefix('Z')\
      .reset_index()

   df = df1.merge(v, how='left', on='A').ffill()

   print (df)


mergeDF(df1, df2)

print (df1)

```

【问题讨论】:

  • 如果您在索引上匹配,请尝试pd.concat([df1, df2], axis=1),如果您在键列上匹配,请尝试加入(内部)而不是合并。
  • 那行不通。创建 2 个 A 列并且不跨 A 进行匹配。
  • 因为 concat 只匹配索引。否则mergejoinset_index 使用on 参数作为答案。
  • 答案看起来很基础,你没研究过吗?为什么要多次导入 pandas,包括在函数内部?

标签: python pandas dataframe


【解决方案1】:

快速:

>>>df1.join(df2.set_index('A'), how='outer', on='A')`
    A   B   C   Z
0   A0  B0  C0  NaN
1   A1  B1  C1  NaN
2   A2  B2  C2  NaN
3   A3  B3  C3  Z4
4   A4  B4  C4  NaN
5   A5  B5  C5  Z5
6   A6  B6  C6  Z6
7   A7  B7  C7  Z7

【讨论】:

    【解决方案2】:

    你可以用比现在更简单的方式来做到这一点:

     pd.merge(df1,df2,how='left',on='A')
    

    您有一个列表,因为您在函数中将 v 转换为 list 并添加了 ffill,它将用列中最后一个非 null 值替换 null 值

    【讨论】:

    • 哇,好用。谢谢。我在这方面投入的时间比要求的要多。非常感谢。
    猜你喜欢
    • 2017-10-21
    • 2019-06-26
    • 1970-01-01
    • 2018-02-21
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多