给定以下 Dataframe :
import numpy as np
df = pd.DataFrame({'price': np.random.random_integers(0, high=100, size=100)})
ranges = [0,10,20,30,40,50,60,70,80,90,100]
df.groupby(pd.cut(df.price, ranges)).count()
输出:
price
price
(0, 10] 9
(10, 20] 11
(20, 30] 11
(30, 40] 9
(40, 50] 16
(50, 60] 7
(60, 70] 10
(70, 80] 9
(80, 90] 14
(90, 100] 4
我怎样才能reset_index
结果并将列名重命名为bins
和counts
呢?谢谢。
bins counts
0 (0, 10] 9
1 (10, 20] 11
2 (20, 30] 11
3 (30, 40] 9
4 (40, 50] 16
5 (50, 60] 7
6 (60, 70] 10
7 (70, 80] 9
8 (80, 90] 14
9 (90, 100] 4
3条答案
按热度按时间3npbholx1#
此代码可以工作但不够简洁,如果您有其他选择,欢迎分享:
输出:
ycl3bljg2#
一种方法是将
rename
用于来自pd.cut
的系列,因此,如果选择列price
用于处理组,则输出为Series
,因此添加Series.reset_index
与2 columns DataFrame
的name
参数:hivapdat3#
https://www.statology.org/pandas-groupby-rename-column/