python - 将列表设置为 Pandas DataFrame 的索引

标签 python pandas list dataframe

我有以下列表:

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/

相关文章:

c# - 从字符串末尾提取整数

python - 此代码中的控制流是什么?

python - SQLAlchemy:过滤存储在 JSONB 字段的嵌套列表中的值

python - 将 CSV 导入 MySQL 数据库 (Django Webapp)

python - 为什么类型化列表的元素访问比使用 Numba 的数组慢得多?

python-3.x - 绘制 pandas 数据框的 x 和 y 列,第三列值确定点的形状

python - 如何在 python 中创建 10,000 个随机坐标?

python - 在 pandas DataFrame 中查找(仅)满足给定条件的第一行

python - Pandas 重新排列数据框,使每列的所有值独立升序排列

python - 如何在列表中查找项目的索引,在 Python 中使用正则表达式搜索项目?