【问题标题】:Type error: "not supported between instances of 'str' and 'float"?类型错误:“在‘str’和‘float’的实例之间不支持”?
【发布时间】:2019-10-24 02:30:22
【问题描述】:

我无法将“MinTemp”列中的值分成 3 组并更新数据框。

“MinTemp”列中的值范围为 -8.2 到 33.9。
我只想要 3 个组,<= 10.0 (mintp1)> 10.0 && <= 22.0 (mintp2) 和 > 22.0 (mintp3)。

from collections import Counter

col         = 'MinTemp'

conditions  = [ data_mod[col] > 22.0, (data_mod[col] > 10.0) & (data_mod[col] <= 22.0), data_mod[col] <= 10.0 ]

choices     = [ 'mintp3', 'mintp2', 'mintp1' ]
data_mod["MinTemp"] = np.select(conditions, choices, default='neutral')

Counter(MinTemp)

TypeError: '>' 在 'str' 和 'float' 的实例之间不支持

【问题讨论】:

  • data_mod[col] 实际上是一个字符串。
  • 虽然它不能直接解决您的错误 - 一旦您将数字作为实际数字,那么如果您想做更复杂的范围,那么看起来 pd.cut 可能值得一看分箱。

标签: python conditional-statements


【解决方案1】:

使用pd.to_numeric 将字符串值转换为允许比较的数值:

df[col] = pd.to_numeric(df[col])

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 1970-01-01
    • 2019-04-14
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 2018-05-19
    • 2019-03-08
    相关资源
    最近更新 更多