首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Python Pandas绑定列

使用Python Pandas绑定列
EN

Stack Overflow用户
提问于 2017-07-24 14:13:09
回答 2查看 167.8K关注 0票数 141

我有一个包含数值的数据框列:

代码语言:javascript
复制
df['percentage'].head()
46.5
44.2
100.0
42.12

我希望将该列显示为bin counts

代码语言:javascript
复制
bins = [0, 1, 5, 10, 25, 50, 100]

我怎样才能得到带有值计数的结果?

代码语言:javascript
复制
[0, 1] bin amount
[1, 5] etc
[5, 10] etc
...
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-07-24 14:14:28

您可以使用pandas.cut

代码语言:javascript
复制
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = pd.cut(df['percentage'], bins)
print (df)
   percentage     binned
0       46.50   (25, 50]
1       44.20   (25, 50]
2      100.00  (50, 100]
3       42.12   (25, 50]

代码语言:javascript
复制
bins = [0, 1, 5, 10, 25, 50, 100]
labels = [1,2,3,4,5,6]
df['binned'] = pd.cut(df['percentage'], bins=bins, labels=labels)
print (df)
   percentage binned
0       46.50      5
1       44.20      5
2      100.00      6
3       42.12      5

numpy.searchsorted

代码语言:javascript
复制
bins = [0, 1, 5, 10, 25, 50, 100]
df['binned'] = np.searchsorted(bins, df['percentage'].values)
print (df)
   percentage  binned
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5

...and,然后是value_countsgroupby,然后聚合size

代码语言:javascript
复制
s = pd.cut(df['percentage'], bins=bins).value_counts()
print (s)
(25, 50]     3
(50, 100]    1
(10, 25]     0
(5, 10]      0
(1, 5]       0
(0, 1]       0
Name: percentage, dtype: int64

代码语言:javascript
复制
s = df.groupby(pd.cut(df['percentage'], bins=bins)).size()
print (s)
percentage
(0, 1]       0
(1, 5]       0
(5, 10]      0
(10, 25]     0
(25, 50]     3
(50, 100]    1
dtype: int64

默认情况下,cut返回categorical

Series.value_counts()这样的Series方法将使用所有类别,即使数据中没有某些类别,operations in categorical

票数 264
EN

Stack Overflow用户

发布于 2022-02-25 00:29:35

我们也可以使用np.select

代码语言:javascript
复制
bins = [0, 1, 5, 10, 25, 50, 100]
df['groups'] = (np.select([df['percentage'].between(i, j, inclusive='right') 
                           for i,j in zip(bins, bins[1:])], 
                          [1, 2, 3, 4, 5, 6]))

输出:

代码语言:javascript
复制
   percentage  groups
0       46.50       5
1       44.20       5
2      100.00       6
3       42.12       5
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45273731

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档