连接中的两个数据帧时出现索引错误

2024-04-26 15:10:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我得到以下错误

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

On代码

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)

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

谢谢!你知道吗


Tags: columnscorepandasdfbaseindexobject错误
1条回答
网友
1楼 · 发布于 2024-04-26 15:10:17

问题是df不是唯一索引的。所以你要么重置索引

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

或者放弃它

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

相关问题 更多 >