简体   繁体   English

熊猫pivot_table到DataFrame

[英]pandas pivot_table to DataFrame

I have data that looks like this 我有看起来像这样的数据

from pandas import DataFrame
data = [{'id': 1, 'label': 0, 'code': 'f1'}, {'id': 1, 'label': 0, 'code': 'f2'},
            {'id': 2, 'label': 1, 'code': 'f3'},
            {'id': 2, 'label': 1, 'code': 'f4'}]
df = DataFrame(data)

>>>
    code  id  label
0   f1   1      0
1   f2   1      0
2   f3   2      1
3   f4   2      1

I want to reshape the data to be something like this (with proper headers and no incorrect id-label associations). 我想将数据重塑为类似的格式(具有正确的标头,并且没有不正确的id-label关联)。

   id label  f1  f2  f3  f4
    1     0   1   1   0   0
    2     1   0   0   1   1

I tried using pivot_table , but with that data looks like this 我尝试使用pivot_table ,但是数据看起来像这样

df['val'] = 1
pt_df = df.pivot_table('val', columns='code', index=['id', 'label'], fill_value=0, dropna=False)

>>>
     f1  f2  f3  f4
1 0   1   1   0   0
  1   0   0   0   0
2 0   0   0   0   0
  1   0   0   1   1

Any suggestions would be helpful! 任何的意见都将会有帮助! Thanks 谢谢

I used unstack, which is essentially pivot... 我使用了unstack,这实际上是关键...

df['vals'] = 1
df = df.set_index(['id' ,'label' ,'code']).unstack('code').fillna(0)
#df = df.reset_index() #to bring out id and label

Here is one way: 这是一种方法:

>>> df.pivot_table(columns='code', index=['id', 'label'], aggfunc=len, fill_value=0)
code      f1  f2  f3  f4
id label                
1  0       1   1   0   0
2  1       0   0   1   1

[2 rows x 4 columns]

If you want the id/label info in columns instead of the index, just use reset_index . 如果要在列中使用ID /标签信息而不是在索引中,只需使用reset_index

Your example data set is small, so it's not clear if this will generalize the way you want. 您的示例数据集很小,因此尚不清楚这是否可以概括您想要的方式。 Basically what it does is it sets the value for each combination of id/label and code to the number of rows of the DataFrame having that combination (eg, the value for id=1, label=0, code=f1 is 1 because there is one row with those values). 基本上,它所做的是将id / label和code的每个组合的值设置为具有该组合的DataFrame的行数(例如,id = 1,label = 0,code = f1的值为1,因为在那里是包含这些值的一行)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM