Nad*_*nag 3 indexing merge concatenation pandas drop
我运行这段代码
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)
Run Code Online (Sandbox Code Playgroud)
但出现此错误:重新索引仅对具有唯一值的索引对象有效有人知道解决方案吗?谢谢
Val*_*_Bo 11
当您运行pd.concat时,每个源 DataFrame 必须具有唯一索引。
首先确定哪个源 DataFrame 具有非唯一索引。对于每个源 DataFrame(假设它是df)运行:
df.index.is_unique
Run Code Online (Sandbox Code Playgroud)
(这是一个属性,而不是一个方法,所以不要加括号)。
false结果意味着此 DataFrame 中的索引不唯一。然后删除具有重复索引值的行:
df = df.loc[~df.index.duplicated(keep='first')]
Run Code Online (Sandbox Code Playgroud)
为了不丢失原始数据,也许您应该将结果保存在新的临时 DataFrame 下,然后用于连接这些临时 DataFrame。