【问题标题】:Transpose and append data in python [closed]在python中转置和附加数据[关闭]
【发布时间】:2021-11-19 19:29:38
【问题描述】:

我有一个如下所示的数据框:

我想在 python 中转置并附加它,使其看起来像这样:

【问题讨论】:

    标签: python dataframe append transpose


    【解决方案1】:
    import pandas as pd
    
    #Data
    col1 = ['Student1', 'Age1', 'Student2', 'Age2']
    col2 = ['Ian', '23', 'John', '34']
    df = pd.DataFrame({'v1':col1, 'v2':col2})
    
    #Split column names using regex based on string versus integer
    df_out = df['v1'].str.split('([A-Za-z]+)', expand=True)[[1, 2]]
    
    #Add data values to new dataframe
    df_out['value'] = df['v2']
    
    #Make pivot table based on the integer split from the column name
    df_out = df_out.pivot(index=2, columns=1)
    
    #Fix indexes and column names
    df_out = df_out.reset_index(drop=True)
    df_out.columns = [i[1] for i in df_out.columns]
    

    【讨论】:

      猜你喜欢
      • 2015-07-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 1970-01-01
      • 2019-03-22
      • 2017-12-21
      相关资源
      最近更新 更多