【问题标题】:Convert column values to NaN using np.where使用 np.where 将列值转换为 NaN
【发布时间】:2019-06-24 07:38:27
【问题描述】:

我无法弄清楚如何在 for 循环中使用来自 np.where 的索引结果。我想使用这个 for 循环来仅更改给定 np.where 索引结果的列的值。

这是一个假设示例,我想在我的数据集中找到某些问题或异常的索引位置,使用 np.where 获取它们的位置,然后在数据帧上运行循环以将它们重新编码为 NaN,而其他所有索引都保持不变。

到目前为止,这是我的简单代码尝试:

import pandas as pd
import numpy as np

# import iris
df = pd.read_csv('https://raw.githubusercontent.com/rocketfish88/democ/master/iris.csv')

# conditional np.where -- hypothetical problem data
find_error = np.where((df['petal_length'] == 1.6) & 
                  (df['petal_width'] == 0.2))

# loop over column to change error into NA
for i in enumerate(find_error):
    df = df['species'].replace({'setosa': np.nan})

# df[i] is a problem but I cannot figure out how to get around this or an alternative

【问题讨论】:

    标签: python python-3.x pandas numpy


    【解决方案1】:

    您可以直接分配给列:

    m = (df['petal_length'] == 1.6) & (df['petal_width'] == 0.2)
    df.loc[m, 'species'] = np.nan
    

    或者,修复你的代码。

    df['species'] = np.where(m, np.nan, df['species'])
    

    或者,使用Series.mask

    df['species'] = df['species'].mask(m)
    

    【讨论】:

    • 谢谢!这真是太棒了!循环上的任何刺伤(我正在努力提高它们,但我真的不擅长循环)。
    • @JohnStud 在某些情况下循环很有用,但通常不建议将它们用于数值数据(尤其是存在矢量化方法时)。循环适用于字符串/正则表达式操作。我在这里有详细的记录:For loops with pandas - When should I care?
    • 再次感谢!非常感谢帮助!
    • 实际上.. 我对这些建议中的每一个都有错误!
    • @JohnStud 好的,这不是特别...有帮助。错误说明了什么?请同时提供错误消息。
    猜你喜欢
    • 1970-01-01
    • 2011-07-04
    • 2014-07-13
    • 2017-04-23
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 2019-12-26
    相关资源
    最近更新 更多