How to change the columns name from a tuple to string?

前端 未结 5 1025
忘掉有多难
忘掉有多难 2021-01-18 06:42

I have used pd.pivot_table in pandas dataframe, and the columns names becomes tuples like (\'A1\', \'B1\'), (\'A1\', \'B2\')... and I want them to

相关标签:
5条回答
  • 2021-01-18 07:05

    Use list comprehension:

    df.columns = ['{}_{}'.format(x[0], x[1]) for x in df.columns]
    print(df)
       A1_B1  A2_B1  A1_B2  A2_B2
    0      0      1      2      3
    1      4      5      6      7
    

    Or:

    df.columns = ['_'.join(x) for x in df.columns]
    print(df)
       A1_B1  A2_B1  A1_B2  A2_B2
    0      0      1      2      3
    1      4      5      6      7
    
    0 讨论(0)
  • 2021-01-18 07:06

    I used this approach:

    mydic = dict() 
    for i,var in enumerate(df.columns):
        if isinstance(var, tuple): 
            mydic[var] = '{}_{}'.format(var[0], var[1])
    df.rename(columns = mydic) 
    

    This allows me to also handle the fact that the second input in my tuple was an integer which had become a float (and been appended an annoying ".0" decimal), by instead rounding off and specifying an integer

    mydic[var] = '{}_{:d}'.format(var[0], round(var[1]))
    
    0 讨论(0)
  • 2021-01-18 07:07

    setup

    df = pd.DataFrame(
        np.arange(8).reshape(2, 4),
        columns=[('A1', 'B1'), ('A2', 'B1'), ('A1', 'B2'), ('A2', 'B2')])
    
    print(df)
    
       (A1, B1)  (A2, B1)  (A1, B2)  (A2, B2)
    0         0         1         2         3
    1         4         5         6         7
    

    rename

    df.rename(columns='_'.join, inplace=True)
    print(df)
    
       A1_B1  A2_B1  A1_B2  A2_B2
    0      0      1      2      3
    1      4      5      6      7
    

    map

    df.columns = df.columns.map('_'.join)
    print(df)
    
       A1_B1  A2_B1  A1_B2  A2_B2
    0      0      1      2      3
    1      4      5      6      7
    
    0 讨论(0)
  • 2021-01-18 07:26

    You can use df.DataFrame.Index.map for this:

    df1.columns.map(lambda t: t[0] + "_" + t[1])
    
    0 讨论(0)
  • 2021-01-18 07:26

    You might need to iterate.

    final=[]
    for x in df.columns.values:
        final.append(x[0]+'_'+x[1])
    df.columns.values = final
    
    0 讨论(0)
提交回复
热议问题