python - Pandas :如何有条件地分配多列?

标签 python pandas numpy

我只想用 nan 替换某些列的负值。最简单的方法可能是:

for col in ['a', 'b', 'c']:
    df.loc[df[col ] < 0, col] = np.nan

df 可以有很多列,我只想对特定列执行此操作。

有没有办法在一行中做到这一点?看起来这应该很容易,但我一直没弄明白。

最佳答案

我不认为你会比这更简单:

>>> df = pd.DataFrame({'a': np.arange(-5, 2), 'b': np.arange(-5, 2), 'c': np.arange(-5, 2), 'd': np.arange(-5, 2), 'e': np.arange(-5, 2)})
>>> df
   a  b  c  d  e
0 -5 -5 -5 -5 -5
1 -4 -4 -4 -4 -4
2 -3 -3 -3 -3 -3
3 -2 -2 -2 -2 -2
4 -1 -1 -1 -1 -1
5  0  0  0  0  0
6  1  1  1  1  1
>>> df[df[cols] < 0] = np.nan
>>> df
     a    b    c  d  e
0  NaN  NaN  NaN -5 -5
1  NaN  NaN  NaN -4 -4
2  NaN  NaN  NaN -3 -3
3  NaN  NaN  NaN -2 -2
4  NaN  NaN  NaN -1 -1
5  0.0  0.0  0.0  0  0
6  1.0  1.0  1.0  1  1

关于python - Pandas :如何有条件地分配多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40090522/

相关文章:

python - 列表理解返回 "generator object..."

python - pandas 0.22,仅重新采样完整的箱子,丢弃部分

python - 带 pandas 的水平条形图左侧的输出表

python - pip install numpy pandas 失败?

python - Django查询关系

python - 在 pandas python 中获取计数

python - Pandas infer_objects() 不会将字符串列转换为数字

python - 在 Python 中查找数组中某个值出现的索引值

python - 如何将 Python 字典对象转换为 numpy 数组

python - 将具有重复索引的系列数据附加到 pandas 数据框列