【问题标题】:How to Convert certain rows in a Pandas Data frame to Columns如何将 Pandas 数据框中的某些行转换为列
【发布时间】:2021-06-11 12:14:52
【问题描述】:

最简单的方法是什么?

【问题讨论】:

标签: python pandas dataframe


【解决方案1】:

您可以使用.to_dict.join 创建一个新的数据框。

# note you'll need to set an index if you only have 1 row.
df_new = pd.DataFrame(df.set_index('H1')['H2'].to_dict(),index=[0]).join(df.iloc[:,2:])


print(new_df)

   a1  a2  a3  H3  H4
0  b1  b2  b3  c1  d1

【讨论】:

    【解决方案2】:

    试试:

    out=df.set_index('H1').unstack().to_frame().drop_duplicates(subset=0).T
    

    最后:

    out.columns=['a1','a2','a3','H3','H4']
    

    out的输出:

        a1  a2  a3  H3  H4
    0   b1  b2  b3  c1  d1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 2020-11-05
      • 1970-01-01
      • 1970-01-01
      • 2023-01-14
      • 1970-01-01
      • 2023-02-10
      相关资源
      最近更新 更多