如何高效将现有DataFrame转换为目标格式的新DataFrame?
DataFrame格式转换解决方案
原DataFrame信息
原DataFrame x 的结构:
x year mar 31, 2024 mar 31, 2023 0 net income 306.000 524.0000 1 net income growth -0.416 -0.0455 2 retained rate NaN NaN 3 pe 419.930 0.0000
行索引与列名:
x.index RangeIndex(start=0, stop=4, step=1) x.columns Index(['year', 'mar 31, 2024', 'mar 31, 2023'], dtype='object')
期望转换后的格式
目标DataFrame new_x:
new_x year net income net income growth retained rate pe 0 mar 31, 2024 306.0 -0.416 NaN 419.93 1 mar 31, 2023 524.0 -0.0455 NaN 0.0
行索引与列名:
new_x.index RangeIndex(start=0, stop=1, step=1) new_x.columns ['year', 'net income', 'net income growth', 'retained rate', 'pe']
高效实现方法
直接转置无法满足需求,需结合索引设置、转置和列名调整完成,具体操作如下:
分步实现
- 将
year列设为DataFrame的索引,让指标名称成为转置后的列名
x.set_index('year', inplace=True)
- 转置DataFrame,并重置行索引为默认序列
new_x = x.T.reset_index()
- 将原索引列重命名为
year,匹配目标格式
new_x.rename(columns={'index': 'year'}, inplace=True)
- 重置行索引为从0开始的连续整数(可选,用于严格匹配目标索引)
new_x.reset_index(drop=True, inplace=True)
一行代码整合
可将上述步骤合并为一行,更简洁高效:
new_x = x.set_index('year').T.reset_index().rename(columns={'index': 'year'}).reset_index(drop=True)
执行后得到的new_x完全符合期望格式。
内容的提问来源于stack exchange,提问作者showkey
相关产品推荐
相关产品推荐

