在 pandas 中进行分档和转换 [英] Binning and transforming in pandas
本文介绍了在 pandas 中进行分档和转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我下面有数据框.
A B
1 1
4 1
5 1
6 2
8 3
15 4
我想对数据框进行分箱和转换到下面.
I would like to binning and transform dataframe to below.
range(A) sum(B)
[0,4) 2
[5,9) 6
[10,14) 0
[15,19) 4
我尝试了groupby+Grouper
,但是我不知道如何进行装箱.
I tried groupby+Grouper
, but I couldnt figure out how to bin.
我可以问一下如何转换数据吗?
Can I ask how to transform data?
推荐答案
You need cut
with parameters right=False
for not include right bins with groupby
:
谢谢您 John Galt ,请添加参数labels
print (pd.cut(df['A'],
bins=[0, 5, 10, 15, 20],
labels=['[0,4)', '[5,9)', '[10,14)', '[15,19)'],
right=False))
0 [0,4)
1 [0,4)
2 [5,9)
3 [5,9)
4 [5,9)
5 [15,19)
Name: A, dtype: category
df = df.groupby([pd.cut(df['A'], bins=[0, 5, 10, 15, 20],
labels=['[0,4)', '[5,9)', '[10,14)', '[15,19)'],
right=False)])
.B.sum()
.fillna(0)
.reset_index()
df.columns = ['range(A)','sum(B)']
print (df)
range(A) sum(B)
0 [0,4) 2.0
1 [5,9) 6.0
2 [10,14) 0.0
3 [15,19) 4.0
这篇关于在 pandas 中进行分档和转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文