【问题标题】:Index error while concatenating two dataframes in pandas在熊猫中连接两个数据帧时出现索引错误
【发布时间】:2019-10-19 12:46:36
【问题描述】:

我收到以下错误

pandas.core.indexes.base.InvalidIndexError: Reindexing only valid with uniquely valued Index objects

关于代码

dfp = pd.concat([df, tdf], axis=1)

我正在尝试将tdf 的列连接到df 的列。

对于这些打印语句

print(df.shape)
print(tdf.shape)
print(df.columns)
print(tdf.columns)
print(df.index)
print(tdf.index)

我得到以下输出:

 (70000, 25)
 (70000, 20)
    Index(['300', '301', '302', '303', '304', '305', '306', '307', '308', '309',
           '310', '311', '312', '313', '314', '315', '316', '317', '318', '319',
           '320', '321', '322', '323', '324'],
          dtype='object')
    Index(['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13',
           '14', '15', '16', '17', '18', '19', '20'],
          dtype='object')
    Int64Index([   0,    1,    2,    3,    4,    5,    6,    7,    8,    9,
                ...
                9990, 9991, 9992, 9993, 9994, 9995, 9996, 9997, 9998, 9999],
               dtype='int64', length=70000)
    RangeIndex(start=0, stop=70000, step=1)

知道是什么问题吗?为什么索引会成为问题?索引应该是相同的,因为我连接列,而不是行。列值似乎完全不同。

谢谢!

【问题讨论】:

标签: python pandas


【解决方案1】:

问题是df 没有唯一索引。所以你需要重置索引

pd.concat([df.reset_index(),tdf], axis=1)

或者放弃

pd.concat([df.reset_index(drop=True),tdf], axis=1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-05
    • 2020-01-20
    • 2019-06-26
    • 2020-08-20
    • 1970-01-01
    • 2017-10-15
    • 2021-01-05
    • 1970-01-01
    相关资源
    最近更新 更多