Python Pandas:除拼接外,如何将单列值转换为行?
将DataFrame最后一列转为行的替代方法
需求说明
给定如下示例DataFrame:
maturity_date simulation simulated_price realized_price 30/06/2010 1 0.539333333 0.611 30/06/2010 2 0.544 0.611 30/06/2010 3 0.789666667 0.611 30/06/2010 4 0.190333333 0.611 30/06/2010 5 0.413666667 0.611
需要将realized_price列转为一行追加到数据末尾,且不使用“单独取出最后一列再拼接”的方式,最终得到如下结果:
maturity_date simulation simulated_price 30/06/2010 1 0.539333333 30/06/2010 2 0.544 30/06/2010 3 0.789666667 30/06/2010 4 0.190333333 30/06/2010 5 0.413666667 30/06/2010 realized_price 0.611
方法一:构造单行DataFrame后合并
直接提取realized_price的取值,构造符合目标结构的单行DataFrame,再与删除原列后的主数据合并:
import pandas as pd # 初始化原DataFrame df = pd.DataFrame({ 'maturity_date': ['30/06/2010']*5, 'simulation': [1,2,3,4,5], 'simulated_price': [0.539333333, 0.544, 0.789666667, 0.190333333, 0.413666667], 'realized_price': [0.611]*5 }) # 构造要追加的行(利用iloc取第一行的固定值) new_row = pd.DataFrame({ 'maturity_date': df['maturity_date'].iloc[0], 'simulation': 'realized_price', 'simulated_price': df['realized_price'].iloc[0] }, index=[len(df)]) # 合并并重置索引 result = pd.concat([df.drop('realized_price', axis=1), new_row], ignore_index=True) print(result)
方法二:直接通过loc添加行
先删除原realized_price列,再直接定位到新行位置插入数据:
import pandas as pd # 初始化原DataFrame df = pd.DataFrame({ 'maturity_date': ['30/06/2010']*5, 'simulation': [1,2,3,4,5], 'simulated_price': [0.539333333, 0.544, 0.789666667, 0.190333333, 0.413666667], 'realized_price': [0.611]*5 }) # 删除原列后直接添加新行 df_modified = df.drop('realized_price', axis=1) df_modified.loc[len(df_modified)] = [df['maturity_date'].iloc[0], 'realized_price', df['realized_price'].iloc[0]] print(df_modified)
说明
两种方法均未采用“单独提取最后一列再转换拼接”的逻辑,而是直接构造目标行结构后完成合并/插入,适合realized_price列值统一的场景。如果该列存在多值,可根据需求调整取值逻辑(如取均值、分组取值等)。
内容的提问来源于stack exchange,提问作者Whitebeard13
相关产品推荐
相关产品推荐

