pandas 行值到列标题 [英] pandas row values to column headers

查看:63
本文介绍了pandas 行值到列标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的 daraframe

I have a daraframe like this

df = pd.DataFrame({'id1':[1,1,1,1,2,2,2],'id2':[1,1,1,1,2,2,2],'value':['a','b','c','d','a','b','c']})

   id1  id2 value
0    1    1     a
1    1    1     b
2    1    1     c
3    1    1     d
4    2    2     a
5    2    2     b
6    2    2     c

我需要变成这种形式

   id1  id2  a  b  c  d
0    1    1  1  1  1  1
1    2    2  1  1  1  0

每个 id 的值变量中可以有任意数量的级别,范围从 1 到 10.如果该 id 不存在级别,则应为 0,否则为 1.

There can be any number of levels in the value variables for each id ranging from 1 to 10. if the level is not present for that id it should be 0 else 1.

我使用的是 anaconda python 3.5,windows 10

I am using anaconda python 3.5, windows 10

推荐答案

如果需要输出 10 仅用于 value 的存在:

If need output 1 and 0 only for presence of value:

您可以使用 get_dummiesSeriesset_index,但这是必要的groupby + GroupBy.max:

You can use get_dummies with Series created by set_index, but then is necessary groupby + GroupBy.max:

df = pd.get_dummies(df.set_index(['id1','id2'])['value'])
       .groupby(level=[0,1])
       .max()
       .reset_index()
print (df)
   id1  id2  a  b  c  d
0    1    1  1  1  1  1
1    2    2  1  1  1  0

groupby, <代码>大小unstack,但有必要与 gt 并通过 astype.最后 reset_indexrename_axis:

Another solution with groupby, size and unstack, but then is necesary compare with gt and convert to int by astype. Last reset_index and rename_axis:

df = df.groupby(['id1','id2', 'value'])
      .size()
      .unstack(fill_value=0)
      .gt(0)
      .astype(int)
      .reset_index()
      .rename_axis(None, axis=1)
print (df)
   id1  id2  a  b  c  d
0    1    1  1  1  1  1
1    2    2  1  1  1  0

<小时>

如果需要计数values:

df = pd.DataFrame({'id1':[1,1,1,1,2,2,2],
                   'id2':[1,1,1,1,2,2,2],
                   'value':['a','b','a','d','a','b','c']})

print (df)
   id1  id2 value
0    1    1     a
1    1    1     b
2    1    1     a
3    1    1     d
4    2    2     a
5    2    2     b
6    2    2     c

df = df.groupby(['id1','id2', 'value'])
       .size()
       .unstack(fill_value=0)
       .reset_index()
       .rename_axis(None, axis=1)
print (df)
   id1  id2  a  b  c  d
0    1    1  2  1  0  1
1    2    2  1  1  1  0

或者:

df = df.pivot_table(index=['id1','id2'], columns='value', aggfunc='size', fill_value=0)
      .reset_index()
      .rename_axis(None, axis=1)
print (df)
   id1  id2  a  b  c  d
0    1    1  2  1  0  1
1    2    2  1  1  1  0

这篇关于pandas 行值到列标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆