【问题标题】:Merging two pandas dataframes results in "duplicate" columns合并两个熊猫数据框会导致“重复”列
【发布时间】:2015-02-03 11:46:48
【问题描述】:

我正在尝试合并两个包含相同键列的数据框。其他一些列也具有相同的标题,尽管行数不相等,并且在合并后这些列与原始标题“重复”,给出后记 _x、_y 等。

有谁知道如何让 pandas 删除下面示例中的重复列?

这是我的python代码:

import pandas as pd

holding_df = pd.read_csv('holding.csv')
invest_df = pd.read_csv('invest.csv')

merge_df = pd.merge(holding_df, invest_df, on='key', how='left').fillna(0)
merge_df.to_csv('merged.csv', index=False)

CSV 文件包含以下内容:

left-dataframe 的第一行 (holding_df)

key, dept_name, res_name, year, need, holding
DeptA_ResA_2015, DeptA, ResA, 2015, 1, 1
DeptA_ResA_2016, DeptA, ResA, 2016, 1, 1
DeptA_ResA_2017, DeptA, ResA, 2017, 1, 1
...

右数据框 (invest_df)

key, dept_name, res_name, year, no_of_inv, inv_cost_wo_ice
DeptA_ResA_2015, DeptA, ResA, 2015, 1, 1000000
DeptA_ResB_2015, DeptA, ResB, 2015, 2, 6000000
DeptB_ResB_2015, DeptB, ResB, 2015, 1, 6000000
...

合并结果

key, dept_name_x, res_name_x, year_x, need, holding, dept_name_y, res_name_y, year_y, no_of_inv, inv_cost_wo_ice
DeptA_ResA_2015, DeptA, ResA, 2015, 1, 1, DeptA, ResA, 2015.0, 1.0, 1000000.0
DeptA_ResA_2016, DeptA, ResA, 2016, 1, 1, 0, 0, 0.0, 0.0, 0.0
DeptA_ResA_2017, DeptA, ResA, 2017, 1, 1, 0, 0, 0.0, 0.0, 0.0
DeptA_ResA_2018, DeptA, ResA, 2018, 1, 1, 0, 0, 0.0, 0.0, 0.0
DeptA_ResA_2019, DeptA, ResA, 2019, 1, 1, 0, 0, 0.0, 0.0, 0.0
...

【问题讨论】:

  • 添加更多的列合并仍然会给你想要的结果吗? merge_df = pd.merge(holding_df, invest_df, on=['key', 'dept_name', 'res_name', 'year'], how='left').fillna(0)
  • _x_y 列源自合并中的左右帧。您需要指定更多列以表明它们是相同的(熊猫不知道)。
  • 您可以将列列表传递给drop,但重命名需要将字典传递给rename
  • 表示值不一致或从 lhs 或 rhs 中丢失,因此您需要重命名 _x 列并删除所有 _y 列,您需要使用 @ 987654334@ 和 rename 建议我可以发布一个动态方法来做到这一点

标签: python pandas


【解决方案1】:

您有额外的带有后缀“_x”和“_y”的列的原因是因为您要合并的列没有匹配的值,所以这种冲突会产生额外的列。在这种情况下,您需要删除额外的“_y”列并重命名“_x”列:

In [145]:
# define our drop function
def drop_y(df):
    # list comprehension of the cols that end with '_y'
    to_drop = [x for x in df if x.endswith('_y')]
    df.drop(to_drop, axis=1, inplace=True)

drop_y(merged)
merged
Out[145]:
               key  dept_name_x  res_name_x   year_x   need   holding  \
0  DeptA_ResA_2015        DeptA        ResA     2015      1         1   
1  DeptA_ResA_2016        DeptA        ResA     2016      1         1   
2  DeptA_ResA_2017        DeptA        ResA     2017      1         1   

    no_of_inv   inv_cost_wo_ice  
0           1           1000000  
1           0                 0  
2           0                 0  
In [146]:
# func to rename '_x' cols
def rename_x(df):
    for col in df:
        if col.endswith('_x'):
            df.rename(columns={col:col.rstrip('_x')}, inplace=True)
rename_x(merged)
merged
Out[146]:
               key  dept_name  res_name   year   need   holding   no_of_inv  \
0  DeptA_ResA_2015      DeptA      ResA   2015      1         1           1   
1  DeptA_ResA_2016      DeptA      ResA   2016      1         1           0   
2  DeptA_ResA_2017      DeptA      ResA   2017      1         1           0   

    inv_cost_wo_ice  
0           1000000  
1                 0  
2                 0 

编辑 如果您将公共列添加到合并中,则它不应产生重复的列,除非这些列上的匹配项不匹配:

merge_df = pd.merge(holding_df, invest_df, on=['key', 'dept_name', 'res_name', 'year'], how='left').fillna(0)

【讨论】:

  • 但它们确实有匹配的值!它们在重复的列中具有匹配的键和匹配的值,然后是仅在右侧数据框中而不在左侧的两个附加列(因此合并)。
  • 不,这不应该发生,重复列仅在键不同时才会出现,因此您的数据有问题
  • 该死,我一定搞砸了,因为向 on 参数添加多列(正如您在评论中首先建议的那样)确实会产生所需的结果。很抱歉,我自己测试时不知道我做错了什么。如果您将您的评论写成简短的答案,我会将其标记为正确。
  • 我刚刚这样做了,我有重复的 _x _y 列,并且匹配值为零。我只是将它放到 Excel 中并创建了新列来检查 this_x = this_y 中的值是否为每一行的 TRUE。所以这不可能是正确的。
【解决方案2】:

即使列的数据相同,左连接后的重复列也存在同样的问题。我做了一个查询,发现即使在 pandas 0.14 中两列都是 NaN,NaN 值也被认为是不同的。但是一旦你升级到 0.15,这个问题就消失了,这就解释了为什么它后来对你有用,你可能升级了。

【讨论】:

    【解决方案3】:

    不完全是答案,但pd.merge 提供了一个参数来帮助您决定应将哪些后缀添加到重叠列中:

    merge_df = pd.merge(holding_df, invest_df, on='key', how='left', suffixes=('_holding', '_invest')).fillna(0)
    

    如果您决定保留两者(或检查保留列的原因),更有意义的名称可能会有所帮助。

    更多参考请见documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-26
      • 1970-01-01
      • 2021-07-28
      • 2017-11-13
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      相关资源
      最近更新 更多