如何在大 pandas 复杂的条件下进行合并 [英] How to pivot with binning with complicated condition in pandas
本文介绍了如何在大 pandas 复杂的条件下进行合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有数据框如下
age type days
1 a 1
2 b 3
2 b 4
3 a 5
4 b 2
6 c 1
7 f 0
7 d 4
10 e 2
14 a 1
首先,我想与年龄合并
年龄
[0〜4]
age type days
1 a 1
2 b 3
2 b 4
3 a 5
4 b 2
然后通过使用类型
sum count
a 6 2
b 9 3
c 0 0
d 0 0
e 0 0
f 0 0
然后我想将此方法应用于另一个binns。
Then I would like to apply this method to another binns.
[5〜9]
[11〜14]
[5~9] [11~14]
我想要的结果在
[0~4] [5~9] [10~14]
sum count sum count sum count
a 6 2 0 0 1 1
b 9 3 0 0 0 0
c 0 0 1 1 0 0
d 0 0 4 1 0 0
e 0 0 0 0 2 1
f 0 0 0 1 0 0
如何做到这一点?
这对我来说非常复杂。
How can this be done? It is very complicated for me..
推荐答案
考虑一个 pivot_table
与 pd.cut
如果您不关心列排序,因为计数和总和不是在箱子下配对。使用操作,您可以更改这样的顺序。
Consider a pivot_table
with pd.cut
if you do not care too much about column ordering as count and sum are not paired together under the bin. With manipulation you can change such ordering.
df['bin'] = pd.cut(df.age, [0,4,9,14])
pvtdf = df.pivot_table(index='type', columns=['bin'], values='days',
aggfunc=('count', 'sum')).fillna(0)
# count sum
# bin (0, 4] (4, 9] (9, 14] (0, 4] (4, 9] (9, 14]
# type
# a 2.0 0.0 1.0 6.0 0.0 1.0
# b 3.0 0.0 0.0 9.0 0.0 0.0
# c 0.0 1.0 0.0 0.0 1.0 0.0
# d 0.0 1.0 0.0 0.0 4.0 0.0
# e 0.0 0.0 1.0 0.0 0.0 2.0
# f 0.0 1.0 0.0 0.0 0.0 0.0
这篇关于如何在大 pandas 复杂的条件下进行合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文