【发布时间】:2022-07-29 07:47:39
【问题描述】:
我在 Python 中有 Pandas 数据框,如下所示(col1 是浮点数据类型):
col1
------
0.04
0.09
100.00
31.34
55.02
80.00
0.0
我想创建一个新列(col2 与 dtype 字符串)将 col1 列中的值分组为范围:
0-10
11-20
21-30
31-40
41-50
51-60
71-80
81-90
91-100
因此,作为结果,我需要如下所示:
col1 | col2
-------|------
0.04 | 0-10
0.09 | 0-10
100.00 | 91-100
31.34 | 31-40
55.02 | 51-60
80.00 | 71-80
0.0 | 0-10
如何在 Python Pandas 中做到这一点?我有如下代码:
bins = [x * 10 for x in range(0, 12)]
df["col2"] = pd.cut(df.col1, bins=bins, include_lowest=True).astype(str)
df.col2 = df.col2.str.replace('(', '').str.replace(']', '').str.replace(' ', '').str.replace(',', '-')
但是当我使用它时,我的结果很糟糕,因为当我在 col2 中有 col1 0.0 时,我的范围是 -0.001-10.0 但它应该是 0-10。我该如何修改它,或者您可能有其他解决方案来获得我需要的结果?
【问题讨论】:
标签: python pandas dataframe cut