【问题标题】:Trying to convert pandas df series of floats to one of four categorical values based on there respective locations in the series quartiles [duplicate]尝试根据系列四分位数中的相应位置将pandas df系列浮点数转换为四个分类值之一[重复]
【发布时间】:2017-06-23 20:16:29
【问题描述】:

我正在尝试编写一个函数,该函数通过一个充满浮点数的 pandas df 系列,并根据它们在系列范围内的位置将它们转换为四个字符串分类变量之一。因此,范围四分位数中的所有值都将转换为低、低中、高中或高。我已经完成了很多方法,但不断收到各种错误消息。最新尝试及其消息如下。如果有人可以偷看并抛出任何想法/修复,我将不胜感激。谢谢!

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")

我在最后一次尝试时收到的错误消息是: AttributeError: 'numpy.float64' 对象没有属性 'replace'

我尝试了各种其他方法来使其成为字符串,例如 astype,但我不断收到错误消息。我是编码新手,所以我确信我很有可能犯了一个愚蠢的错误,但我很感激任何人都可以给我的帮助。干杯。

【问题讨论】:

  • 你如何分类59862.5

标签: python pandas


【解决方案1】:

我会使用矢量化pd.cut() 方法:

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

【讨论】:

  • 感谢 MaxU!那效果很好。而且我学到了一种新方法,我相信我会经常使用它:)。
  • 刚刚做了。抱歉,这是我的第一个 stackoverflow 问题。祝你有美好的一天。
猜你喜欢
  • 2019-02-27
  • 2019-08-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
  • 2019-06-25
相关资源
最近更新 更多