我有以下列表:
index_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
我想用它来定义以下 DataFrame 的索引:
df = pd.DataFrame(index= [0,1,4,7])
DataFrames 索引对应于列表中的一个条目。最终结果应如下所示:
df_target = pd.DataFrame(index= ['a','b','e','h'])
我尝试了一些 pandas 的内置函数,但没有成功。
最佳答案
使用Index.map
使用 enumerate
创建的字典:
target_df = pd.DataFrame(index=df.index.map(dict(enumerate(index_list))))
print (target_df)
Empty DataFrame
Columns: []
Index: [a, b, e, h]
如果需要更改现有 DataFrame 中的索引:
df = pd.DataFrame({'a':range(4)}, index= [0,1,4,7])
print (df)
a
0 0
1 1
4 2
7 3
df = df.rename(dict(enumerate(index_list)))
print (df)
a
a 0
b 1
e 2
h 3
关于python - 将列表设置为 Pandas DataFrame 的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73077637/