python - 基于保留重复项的公共(public)列的查找合并两个 dfs

标签 python pandas database dataframe pyspark

我的 df1 为:

import pandas as pd

index = [0, 1, 2, 3]
columns = ['col0', 'col1']
data = [['A', 'D'],
        ['A', 'D'],
        ['C', 'F'],
        ['A', 'D']
       ]
df1 = pd.DataFrame(data, index, columns)
   col0 col1
0   A   D
1   B   E
2   C   F
3   A   D

我的 df2 为:

index = [0, 1]
columns = ['col1', 'col2', 'col3']
data = [['D', 'XX', 'YY'],
        ['E', 'XXX', 'YYY']
       ]
df2 = pd.DataFrame(data, index, columns)
   col1 col2 col3
0   D   XX    YY
1   E   XXX   YYY

df1和df2的长度不同,df1有很多重复的值行,我想根据column1查找值并从df2获取其他列的结果。

结果 df3 应如下所示:

index = [0, 1, 2, 3]
columns = ['col0', 'col1', 'col2', 'col3']
data = [['A', 'D', 'XX', 'YY'],
        ['B', 'E', 'XXX', 'YYY'],
        ['C', 'F', 'nan', 'nan'],
        ['A', 'D', 'XX', 'YY']
       ]
df3 = pd.DataFrame(data, index, columns)
  col0  col1  col2  col3
0   A   D     XX    YY
1   B   E     XXX   YYY
2   C   F     nan   nan
3   A   D     XX    YY

如果 df1 和 df2 的长度相同,那么这对我有用:

df3 = pd.merge(df1, df2, left_on=["col0", "col1"], right_index=True, how="left")

每当 col1 上有匹配项时,无论有多少重复项,我都想为所有重复项填充其余列,除非没有匹配项,因此为 Nan。

我总是可以在 df.iterrows() 中查找 id,row ,但这不会适合我的情况,我在 df1 上有 1,41,000 行。

也对 Pyspark 解决方案开放。

提前致谢。

最佳答案

您可以使用合并,但请指定 left_onright_on。这将指定合并时要比较的值,left_on 是第一个数据帧的列,right_on 是第二个数据帧的列,并且 how=left 使其作为左连接运行。

import pandas as pd

index = [0, 1, 2, 3]
columns = ['col0', 'col1']
data = [['A', 'D'],
        ['A', 'E'],
        ['C', 'F'],
        ['A', 'D']
       ]
df1 = pd.DataFrame(data, index, columns)

index = [0, 1]
columns = ['col1', 'col2', 'col3']
data = [['D', 'XX', 'YY'],
        ['E', 'XXX', 'YYY']
       ]
df2 = pd.DataFrame(data, index, columns)
df3 = pd.merge(df1, df2, left_on="col1", right_on="col1", how="left")
print(df3)

#output
  col0 col1 col2 col3
0    A    D   XX   YY
1    A    E  XXX  YYY
2    C    F  NaN  NaN
3    A    D   XX   YY

关于python - 基于保留重复项的公共(public)列的查找合并两个 dfs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75874626/

相关文章:

database - JPA 实体 - 指定持久性单元?

sql - 获取包含特定表名的所有模式的列表

php - 文本搜索以与 Mysql 数据库表进行比较

python - 如何使用extract_links()从编码为 'gb2312'的网页中获取url

python - 在 pandas groupby 之后并行化应用

python - 如何提取并引用 python 模块中定义的变量?

python - 用 Pane 数据填充数据框

python - 关于pandas条件计算的问题

python - 在 pandas dataframe python 中使用 pii 匿名化特定列

python - 尝试使用 Anaconda-navigator 安装 Tensorflow 但在导航器中找不到该包