【问题标题】:is there a way to have np.where skip any strings that contain non numerics?有没有办法让 np.where 跳过任何包含非数字的字符串?
【发布时间】:2020-11-11 00:26:48
【问题描述】:

我正在尝试将数据框中的列从百分比 int 转换为分类。使用 np.where 我可以将它存储一次。由于 int 被转换为 str,任何进一步拆分数据的额外尝试都会失败。 我不知道如何跳过带有无法转换为整数的单词的字符串。 虽然 (x).astype(int) 适用于“26”,但它会为“低”抛出一个基数为 10 的错误

我正在尝试做的事情:

life_data = [10, 50, 95, 19, 89](其实是我正在导入的一个csv文件)

第一次通过;所有数据都从 int 转换为 str

life_data = np.where(life_data < 50, 'low', life_data)

print(life_data)

['low', '50', '95', 'low', '89']

由于单词 'low' 试图转换为 int,下一次尝试失败,抛出 base 10 错误

life_data = np.where(50 >= life_data.astype(int) < 91, 'mid', life_data)

预期输出(但失败) ['low', 'mid', '95', 'low', 'mid']

在尝试用 真值错误省略 'low' 时也会失败。我尝试使用 a.any() 或 a.all(),但似乎无法正确包装。

life_data = np.where(life_data != low and 50 >= life_data.astype(int) < 91, 'mid', life_data)

预期输出(但失败) ['low', 'mid', '95', 'low', 'mid']

【问题讨论】:

  • 看看np.select(或使用嵌套np.where),这样您就可以在一次调用中指定“低”、“中”和大概“高”,从而避免所有这个

标签: python pandas numpy data-science


【解决方案1】:

在这里,这应该可以工作:

在使用 np.where() 之前,添加一个 if 语句,说明

if ![insert your string here].isnumeric():
        [insert handling code here]

【讨论】:

    【解决方案2】:

    如果你想避免数值解析时出错,试试

    pd.to_numeric(['low', 'mid', '95', 'low', 'mid'], errors='coerce')      
    

    输出

    [nan, nan, 95., nan, nan]
    

    你会发现 cut 函数很有用。

    life_data = pd.Series([10, 50, 95, 19, 89])
    pd.cut(life_data, right=False,
           bins=[0, 50, 91, np.inf],
           labels=['Low', 'Med', 'High'])
    

    输出

    0     Low
    1     Med
    2    High
    3     Low
    4     Med
    

    【讨论】:

      猜你喜欢
      • 2016-09-20
      • 2020-09-10
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-30
      相关资源
      最近更新 更多