【问题标题】:Convert single row into pandas column将单行转换为熊猫列
【发布时间】:2021-08-08 13:19:18
【问题描述】:

我有与给定简单数据框类似的数据框文件。我想选择单行数据并转换为重新排列的列。

创建的问题数据框是 df1:

import pandas as pd

data =[['Name','john','riya','alex'],
       ['Age',28, 24, 34],[ 'Month','February','January','March'],
       ['Status','M','F','M']] 

df = pd.DataFrame(data,columns=['index',0,0,0])
df1 = df.set_index('index')

我想将数据框重新排列为 df2,如下所示:

desired_data = {'January' :pd.Series(['riya', 24, 'F'], index=['Name', 'Age','Status']),
                'February':  pd.Series(['john', 28, 'M'], index=['Name', 'Age','Status']),
                'March' : pd.Series(['alex', 34, 'M'], index=['Name', 'Age','Status'])}

df2 = pd.DataFrame(desired_data)

【问题讨论】:

    标签: python pandas database dataframe time-series


    【解决方案1】:

    ordered categoricals 用于原始排序值:

    cats = ['January',
     'February',
     'March',
     'April',
     'May',
     'June',
     'July',
     'August',
     'September',
     'October',
     'November',
     'December']
    
    df1 = (df1.set_axis(pd.Categorical(df1.loc['Month'], ordered=True, categories=cats), axis=1)
              .drop('Month')
              .sort_index(axis=1)
              .rename_axis(index=None, columns=None))
    print (df1)
          January February March
    Name      riya     john  alex
    Age         24       28    34
    Status       F        M     M
    

    或者创建用于排序的字典:

    cats = ['January',
     'February',
     'March',
     'April',
     'May',
     'June',
     'July',
     'August',
     'September',
     'October',
     'November',
     'December']
    
    d = {v: k for k, v in dict(enumerate(cats)).items()}
    print (d)
    {'January': 0, 'February': 1, 'March': 2, 'April': 3, 'May': 4, 'June': 5, 'July': 6,
     'August': 7, 'September': 8, 'October': 9, 'November': 10, 'December': 11}
    
    df1 = (df1.set_axis(df1.loc['Month'], axis=1)
              .drop('Month')
              .reindex(sorted(df1.loc['Month'], key=d.get), axis=1)
              .rename_axis(index=None, columns=None))
    
    print (df1)
           January February March
    Name      riya     john  alex
    Age         24       28    34
    Status       F        M     M
    

    感谢@SeaBean 提供另一个解决方案:

    df1 = (df1.set_axis(df1.loc['Month'], axis=1)
              .drop('Month')
              .sort_index(axis=1, key=lambda x: pd.to_datetime(x, format='%B').month)
              .rename_axis(index=None, columns=None))
    

    【讨论】:

    • 另一种按月份文本对列进行排序的方法是将key= 参数与 lambda 函数一起使用,例如df1.sort_index(axis=1, key=lambda x: pd.to_datetime(x, format='%B').month)
    • @SeaBean - 谢谢,经过测试并添加到解决方案中。
    【解决方案2】:
    df1.columns = df1.iloc[2]
    df1 = df1.drop(df1.index[2])
    df1 = df1.rename_axis(None).rename_axis(None,axis='columns')
    df1
    

    输出

            February    January March
    Name    john        riya    alex
    Age     28          24      34
    Status  M           F       M
    

    【讨论】:

    • 非常感谢,但是否可以在列名中指定月份顺序,因为它是按字母顺序排列的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-14
    • 2019-05-22
    • 2022-12-18
    • 2017-04-08
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    相关资源
    最近更新 更多