如何修改Pandas DataFrame行索引:将0改为Color、1改为Size?
解决Pandas DataFrame行索引修改问题
最简单的解决方案:创建后直接替换索引
你可以在生成DataFrame之后,直接给index属性赋值来替换行索引,代码如下:
import pandas as pd clothes = {"shirt": ["red", "M"], "sweater": ["yellow", "L"], "jacket": ["black", "L"]} df = pd.DataFrame.from_dict(clothes) # 直接替换行索引 df.index = ['Color', 'Size'] print(df)
运行后就能得到行索引为Color和Size的DataFrame。
为什么你的原代码无效?
你用pd.DataFrame.from_dict(clothes, index=['color', 'size'])没效果,是因为from_dict默认的orient参数是'columns'——这个模式下,字典的键会被作为列名,值作为列数据,此时传入的index参数不会生效(这个参数仅在orient='index'模式下用来指定行索引),所以才会出现索引名称错误或无效果的情况。
另一种创建时直接指定索引的方法
如果你想在创建DataFrame的同时就设置好索引,可以调整orient参数并转置数据:
import pandas as pd clothes = {"shirt": ["red", "M"], "sweater": ["yellow", "L"], "jacket": ["black", "L"]} # 先以衣服为行索引,Color/Size为列,再转置得到目标结构 df = pd.DataFrame.from_dict(clothes, orient='index', columns=['Color', 'Size']).T print(df)
这种方式也能得到目标结果,但相比第一种直接修改索引的方法,步骤稍繁琐。
内容的提问来源于stack exchange,提问作者errEstiak
相关产品推荐
相关产品推荐

