python - 在 Python 中分箱后返回范围的下限或上限

标签 python pandas dataframe range binning

我使用 pd.cut 将以下 df 转换为 bin:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randint(0,100,size=(5, 4)), columns=list('ABCD'))
print(df)
newDF = pd.cut(df.A, 2, precision=0)
print(newDF)

A   B   C   D
0  83  43  99  85
1   6  57  44  45
2   5  72  10  53
3  24  50  23  18
4  75  25  96  27
0    (44.0, 83.0]
1     (5.0, 44.0]
2     (5.0, 44.0]
3     (5.0, 44.0]
4    (44.0, 83.0]

有没有办法返回范围的下限或上限而不是整个范围?例如,从上面的例子:

0    44.0
1    5.0
2    5.0
3    5.0
4    44.0

最佳答案

使用Series.map :

pd.cut(df.A, 2, precision=0).map(lambda x: x.left)

pd.IntervalIndex

s = pd.cut(df.A, 2, precision=0)
pd.Series(data=pd.IntervalIndex(s).left, index = s.index)
<小时/>
#print(df)
#
#
#    A   B   C   D
#0  26  70  28   2
#1  49  42  56  28
#2  48  26  40  19
#3   3  50  17   3
#4  20  34  54  42
#
#
#pd.cut(df.A, 2, precision=0).map(lambda x: x.left)
#
#0     3.0
#1    26.0
#2    26.0
#3     3.0
#4     3.0
#Name: A, dtype: category
#Categories (2, float64): [3.0 < 26.0]

关于python - 在 Python 中分箱后返回范围的下限或上限,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60726812/

相关文章:

python - 我无法将字段命名为 "from"

python - 提取动词短语中的平均单词数

python Pandas : how to find rows in one dataframe but not in another?

python - Pandas:使用 MultiColumn 进行分组

python - 根据多行条件比较两个不同的数据帧

python - 如何使用 pandas df.plot.scatter 制作带有子图的图形

python - 使用 strip 函数删除通过正则表达式获得的字符串的一部分

python - GCP/Py : determine when compute engine instance is actually ready to be used (not "RUNNING")

python - 使 df.apply 成为索引和列函数的最佳方法

Python 数据帧 : How to connect different columns with the same name and merge them into one column