[英]MultiLevel index to columns : getting value_counts as columns in pandas
In a very general sense, the problem I am looking to solve is changing one component of a multi-level index into columns. 在一般意义上,我要解决的问题是将多级索引的一个组件更改为列。 That is, I have a
Series
that contains a multilevel index and I want the lowest level of the index changed into columns in a dataframe
. 也就是说,我有一个包含多级索引的
Series
,我希望将索引的最低级别更改为dataframe
列。 Here is the actual example problem I'm trying to solve, 这是我想要解决的实际示例问题,
Here we can generate some sample data: 在这里我们可以生成一些示例数据:
foo_choices = ["saul", "walter", "jessee"]
bar_choices = ["alpha", "beta", "foxtrot", "gamma", "hotel", "yankee"]
df = DataFrame([{"foo":random.choice(foo_choices),
"bar":random.choice(bar_choices)} for _ in range(20)])
df.head()
which gives us, 这给了我们,
bar foo
0 beta jessee
1 gamma jessee
2 hotel saul
3 yankee walter
4 yankee jessee
...
Now, I can groupby bar
and get value_counts of the foo
field, 现在,我可以组合
bar
并获取foo
字段的value_counts,
dfgb = df.groupby('foo')
dfgb['bar'].value_counts()
and it outputs, 它输出,
foo
jessee hotel 4
gamma 2
yankee 1
saul foxtrot 3
hotel 2
gamma 1
alpha 1
walter hotel 2
gamma 2
foxtrot 1
beta 1
But what I want is something like, 但我想要的是像,
hotel beta foxtrot alpha gamma yankee
foo
jessee 1 1 5 4 1 1
saul 0 3 0 0 1 0
walter 1 0 0 1 1 0
My solution was to write the following bit: 我的解决方案是写下面的内容:
for v in df['bar'].unique():
if v is np.nan: continue
df[v] = np.nan
df.ix[df['bar'] == v, v] = 1
dfgb = df.groupby('foo')
dfgb.count()[df['bar'].unique()]
我想你想要:
dfgb['bar'].value_counts().unstack().fillna(0.)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.