Python 尝试根据系列四分位数中的相应位置,将浮点系列转换为四个分类值之一
我正在尝试编写一个函数,它将遍历一个充满浮点数的系列,并根据它们在系列范围内的位置将它们转换为四个字符串分类变量之一。因此,四分位数范围内的所有值都将转换为low、low_mid、high_mid或high。我已经用了很多方法,但不断收到各种错误消息。下面是最新的尝试及其消息。如果有人能看一眼并抛出任何想法/修复方案,我将不胜感激。谢谢Python 尝试根据系列四分位数中的相应位置,将浮点系列转换为四个分类值之一,python,pandas,Python,Pandas,我正在尝试编写一个函数,它将遍历一个充满浮点数的系列,并根据它们在系列范围内的位置将它们转换为四个字符串分类变量之一。因此,四分位数范围内的所有值都将转换为low、low_mid、high_mid或high。我已经用了很多方法,但不断收到各种错误消息。下面是最新的尝试及其消息。如果有人能看一眼并抛出任何想法/修复方案,我将不胜感激。谢谢 def makeseriescategorical(x): for i in x: if i < 59863.0:
def makeseriescategorical(x):
for i in x:
if i < 59863.0:
str(i)
i.replace(i, "low")
elif i > 59862.0 and i < 86855.0:
str(i)
i.replace(i, "low_mid")
elif i > 86854.0 and i < 125250.0:
str(i)
i.replace(i, "high_mid")
elif i > 125249.0 and i < 332801:
str(i)
i.replace(i, "high")
def MakeSeriesCategory(x):
对于x中的i:
如果i<59863.0:
str(i)
i、 替换(i,“低”)
如果i>59862.0且i<86855.0:
str(i)
i、 替换(i,“低中”)
如果i>86854.0且i<125250.0:
str(i)
i、 替换(i,“高/中”)
如果i>125249.0且i<332801:
str(i)
i、 替换(i,“高”)
我上次尝试时收到的错误消息是:
AttributeError:'numpy.float64'对象没有属性'replace'
我尝试了各种其他方法使它成为一个字符串,比如astype,但我总是出错。我对编码是新手,所以我确信我很有可能犯了一个愚蠢的错误,但我非常感谢任何人能给我的帮助。干杯。我会使用矢量化方法:
您将如何分类
59862.5
?谢谢MaxU!这很有效。我学到了一种新的方法,我相信我会用很多:)。刚刚学过。对不起,这是我的第一个问题。祝您今天过得愉快。
In [51]: df = pd.DataFrame(np.random.randint(0, 332801, 10), columns=['val'])
In [52]: df
Out[52]:
val
0 230852
1 140030
2 231657
3 73146
4 240890
5 328660
6 194801
7 240684
8 44439
9 35558
In [53]: bins = [-np.inf, 59863.0, 86855.0, 125250.0, 332801]
In [54]: labels=['low','low_mid','high_mid','high']
In [55]: df['category'] = pd.cut(df.val, bins=bins, labels=labels)
In [56]: df
Out[56]:
val category
0 230852 high
1 140030 high
2 231657 high
3 73146 low_mid
4 240890 high
5 328660 high
6 194801 high
7 240684 high
8 44439 low
9 35558 low
In [57]: df.dtypes
Out[57]:
val int32
category category
dtype: object