我只想用 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/