pandas 行值到列标题 [英] pandas row values to column headers
问题描述
我有一个像这样的 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
推荐答案
如果需要输出 1
和 0
仅用于 value
的存在:
If need output 1
and 0
only for presence of value
:
您可以使用 get_dummies
和 Series
由 set_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_index
和 rename_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
<小时>
如果需要计数value
s:
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屋!