【问题标题】:How to divide values in one column into compartments and create new column in DataFrame in Pandas Python?如何将一列中的值划分为隔间并在 Pandas Python 的 DataFrame 中创建新列?
【发布时间】: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


    【解决方案1】:

    由于您已将参数 include_lowest = True 传递给 df.cut(),因此值 0.00 将映射到区间 0 (included) - 10,当转换为字符串时,该区间以 (-0.001 - 10] 表示。

    为了得到你想要的东西,将此行更改为df["col2"] = pd.cut(df.col1, bins=bins, include_lowest=False).astype(str) 并使用df.loc[df['col2'] == 'nan'] = '0-10' 分别处理零的映射

    演示代码link

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 2022-01-12
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多