gpt4 book ai didi

pandas - 重新索引仅对具有唯一值的索引对象有效

转载 作者:行者123 更新时间:2023-12-05 02:32:27 24 4
gpt4 key购买 nike

我运行这段代码

esg_fm_barron = pd.concat([barron_clean.drop(columns = "10 year return", inplace = False),ESG_fixed.drop(columns = 'Name',inplace = False), financial_clean.drop(columns = 'Name',inplace = False)], axis = 'columns', join = 'inner')
esg_fm_barron.rename(columns={'Average (Current)': "Total ESG Score"}, inplace=True)
esg_fm_barron.head(3)

但出现此错误:重新索引仅对具有唯一值的索引对象有效有人知道解决方案吗?谢谢

最佳答案

当您运行 pd.concat 时,每个源 DataFrame 必须具有唯一索引。

首先识别哪个源DataFrame有一个非唯一索引。对于每个源 DataFrame(假设它是 df)运行:

df.index.is_unique

(这是一个属性,而不是一个方法,所以不加括号)。

false 结果表示此 DataFrame 中的索引不唯一。然后删除具有重复索引值的行:

df = df.loc[~df.index.duplicated(keep='first')]

为了不丢失原始数据,也许你应该将结果保存在一个新的临时 DataFrame,然后用于连接这些临时 DataFrame。

关于pandas - 重新索引仅对具有唯一值的索引对象有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71240439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com