【问题标题】:pandas dataframe reshape after pivot大熊猫数据框在枢轴后重塑
【发布时间】:2016-07-07 08:03:52
【问题描述】:

枢轴代码:

result = pandas.pivot_table(result, values=['value'], index=['index'], columns=['columns'], fill_value=0)

结果:

        value   value   value   
columns col1    col2    col3    
index
idx1    14      1       1
idx2    2       0       1
idx3    6       0       0  

我试过了:

result.columns = result.columns.get_level_values(1)

然后我得到了这个:

columns col1    col2    col3
index
idx1    14      1       1
idx2    2       0       1
idx3    6       0       0  

其实我想要的是这个:

index   col1    col2    col3
idx1    14      1       1
idx2    2       0       1
idx3    6       0       0

有没有办法做到这一点?帮助真的很感激。提前谢谢你。

【问题讨论】:

  • 抱歉,您在抱怨index 这个名字吗?你可以通过df.index.name = None 删除它
  • 实际上我希望保留“索引”,但“列”(列名)会消失
  • 你可以做df.columns.name = None
  • 是的,这就是我所需要的。谢谢 EdChum。请在下面发布,以便我解决这个问题

标签: python pandas dataframe pivot-table


【解决方案1】:

您需要删除 index name by rename_axispandas 0.18.0 中的新功能):

df = df.rename_axis(None)

如果需要还删除columns name,请使用:

df = df.rename_axis(None, axis=1)

如果使用旧版本的 pandas,请使用:

df.columns.name = None
df.index.name = None

示例(如果从pivot_table 中删除[],则从列中删除Multiindex):

print (result)
   index columns  value
0      1    Toys      5
1      2    Toys      6
2      2    Cars      7
3      1    Toys      2
4      1    Cars      9

print (pd.pivot_table(result, index='index',columns='columns',values='value', fill_value=0)
         .rename_axis(None)
         .rename_axis(None, axis=1))

   Cars  Toys
1     9   3.5
2     7   6.0         

如果使用[],获取:

result = pd.pivot_table(result, values=['value'], index=['index'], columns=['columns'], fill_value=0)
            .rename_axis(None)
            .rename_axis((None,None), axis=1)
print (result)        
  value     
   Cars Toys
1     9  3.5
2     7  6.0     

【讨论】:

  • 如果从pivot_table 中删除[],则输出列中没有Multiindex,因此不需要result.columns = result.columns.get_level_values(1)。请检查编辑。
【解决方案2】:

考虑这个数据框:

results = pd.DataFrame(
    [
        [14, 1, 1],
        [2, 0, 1],
        [6, 0, 0]
    ],
    pd.Index(['idx1', 'idx2', 'idx3'], name='index'),
    pd.MultiIndex.from_product([['value'], ['col1', 'col2', 'col3']], names=[None, 'columns'])
)

print results

        value          
columns  col1 col2 col3
index                  
idx1       14    1    1
idx2        2    0    1
idx3        6    0    0

那么你只需要:

print results.value.rename_axis(None, 1)  # <---- Solution

       col1  col2  col3
index                  
idx1     14     1     1
idx2      2     0     1
idx3      6     0     0

【讨论】:

    猜你喜欢
    • 2017-04-08
    • 1970-01-01
    • 2020-04-13
    • 2020-06-19
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多