假设我有以下数据框:
In [1]: df
Out[1]:
apple banana cherry
0 0 3 good
1 1 4 bad
2 2 5 good
这按预期工作:
In [2]: df['apple'][df.cherry == 'bad'] = np.nan
In [3]: df
Out[3]:
apple banana cherry
0 0 3 good
1 NaN 4 bad
2 2 5 good
但这不会:
In [2]: df[['apple', 'banana']][df.cherry == 'bad'] = np.nan
In [3]: df
Out[3]:
apple banana cherry
0 0 3 good
1 1 4 bad
2 2 5 good
为什么?如何在不必写出两行的情况下实现“apple”和“banana”值的转换,如
In [2]: df['apple'][df.cherry == 'bad'] = np.nan
In [3]: df['banana'][df.cherry == 'bad'] = np.nan