python - Pandas:如何组合连接两个数据框

标签 python pandas

我有两个数据帧,我想以组合方式组合(即将一个 df 的每一行组合到另一个 df 的每一行)。我可以通过合并“key”来做到这一点,但我的解决方案显然很麻烦。我正在寻找一种更直接、甚至是Python式的方法来处理此操作。有什么建议吗?

MWE:

fred = pd.DataFrame({'A':[1., 4.],'B':[2., 5.], 'C':[3., 6.]})
print(fred)
    A    B    C
0  1.0  2.0  3.0
1  4.0  5.0  6.0

jim = pd.DataFrame({'one':['a', 'c'],'two':['b', 'd']})
print(jim)
   one two
0   a   b
1   c   d


fred['key'] = [1,2]
jim1 = jim.copy()
jim1['key'] = 1
jim2 = jim.copy()
jim2['key'] = 2
jim3 = jim1.append(jim2)

jack = pd.merge(fred, jim3, on='key').drop(['key'], axis=1)
print(jack)
    A    B    C   one two
0  1.0  2.0  3.0   a   b
1  1.0  2.0  3.0   c   d
2  4.0  5.0  6.0   a   b
3  4.0  5.0  6.0   c   d

最佳答案

您可以通过合并等于相同值的 key 列,将 fred 的每一行与 jim 的每一行连接起来(比如说,1)对于每一行:

In [16]: pd.merge(fred.assign(key=1), jim.assign(key=1), on='key').drop('key', axis=1)
Out[16]: 
     A    B    C one two
0  1.0  2.0  3.0   a   b
1  1.0  2.0  3.0   c   d
2  4.0  5.0  6.0   a   b
3  4.0  5.0  6.0   c   d

关于python - Pandas:如何组合连接两个数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49638015/

相关文章:

python - 在大型数据集上使用 pandas 滚动 max 非常慢

python - Pandas - 通过将组中的重复项目视为新项目来对组内的项目进行排名

python - 如何从 'pandas.core.frame.DataFrame' 中消除第一列

python - Pandas 系列填充默认日期

python - 如何从 Pandas 数据框中删除重复行但仅在某个范围内?

python - 我应该如何在 Google App Engine 项目中导入 django.middleware 类?

python - 合并排序中的不可排序类型 "int() <= list()"

Python Pandas 使用文本文件创建 Dataframe

python - 将 Pandas 数据框转换为包含索引、数据和列的列表列表

Python 2.7 + Django 1.7 + PostgreSQL 9.3 : I'm getting a UnicodeEncodeError when trying to save some text to my database. 给出了什么?