Pandas数据框架集合索引不能正常工作



我有3个数据集,我需要连接在一起按国家名称:

merged_df = pd.merge(Energy, GDP, on="Country")
merged_df2 = pd.merge(merged_df, ScimEn, on="Country")
merged_df2.set_index('Country')

赋值说明我必须:

  1. 只选择特定列
  2. 排序
  3. 仅根据排名取前15行。

所以我这样做了:

df3 = merged_df2[['Country','Rank' ,'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', 'Energy Supply', 'Energy Supply per Capita', '% Renewable', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015']]
df3.set_index('Country')
df4 = df3[['Country','Rank' ,'Documents', 'Citable documents', 'Citations', 'Self-citations', 'Citations per document', 'H index', 'Energy Supply', 'Energy Supply per Capita', '% Renewable', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015']]

df4 = df4.sort_values(by=['Rank'], ascending=True)
df4.set_index('Country')

print(df4.index)

然后打印:

Int64Index([3, 14, 9, 13, 11, 2, 5, 6, 4, 10, 8, 12, 7, 0, 1], dtype='int64')

但它应该打印1,1,2,3,4…15

我错过了什么?

你需要分配回:

df4 = df4.set_index('Country')

或:

df4.set_index('Country', inplace=True)

您需要将inplace参数设置为true。

df3.set_index('Country',inplace = True)

最新更新