【发布时间】: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