【问题标题】:Pandas Concat returning "InvalidIndexError: Reindexing only valid with uniquely valued Index objects" ErrorPandas Concat 返回“InvalidIndexError:重新索引仅对唯一值索引对象有效”错误
【发布时间】:2021-12-23 23:55:21
【问题描述】:

我有两个具有相同标头的数据框。 当我尝试连接 (pd.concat()) 这两个 dfs (df1, df2) 时,出现错误:

"InvalidIndexError: Reindexing only valid with uniquely valued Index objects"

我发现问题在于每个数据框中都有重复的列名。 示例:

df1

respondent ID - Column1 - Column2 - Column3 - Column1 - Column2 - Column3

df2

respondent ID - Column1 - Column2 - Column3 - Column1 - Column2 - Column3

理论上,我只是想在df1下面添加df2的数据(没有df2 ofc的headers)

如何绕过这个?有什么想法吗?

【问题讨论】:

标签: python python-3.x pandas dataframe concatenation


【解决方案1】:

重复的列应该不是问题(即使是ignore_index=False):

df1 = pd.DataFrame([range(7)], columns=['respondent ID', 'Column1', 'Column2', 'Column3', 'Column1', 'Column2', 'Column3'])
df2 = pd.DataFrame([['2']*7], columns=['respondent ID', 'Column1', 'Column2', 'Column3', 'Column1', 'Column2', 'Column3'])
pd.concat([df1, df2], ignore_index=True)

输出:

  respondent ID Column1 Column2 Column3 Column1 Column2 Column3
0             0       1       2       3       4       5       6
1             2       2       2       2       2       2       2

【讨论】:

    【解决方案2】:

    你可以使用这个解决方案:

    df1 = df1.append(df2, ignore_index=True)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-10-23
      • 2021-05-22
      • 2019-04-09
      • 1970-01-01
      • 2021-07-18
      • 1970-01-01
      • 2020-07-26
      相关资源
      最近更新 更多