我想用dN替换df中介于-0.5和0.5之间的所有值。
对于后一种情况,这种解决方案很有效:
df[df < 0.5] = np.nan
但是,我不能弄清楚如何添加第二个条件,如:
df[-0.5 < df < 0.5] = np.nan
非常感谢任何帮助!
感谢。
答案 0 :(得分:2)
您所需要的只是基于两个条件df < 0.5
和df > -0.5
进行索引,例如:
df[(df < 0.5) & (df > -0.5)] = np.nan
例如:
import pandas as pd
import numpy as np
# Example df
df = pd.DataFrame(data={'data1':2*np.random.randn(100),
'data2':2*np.random.randn(100)})
# Show example with all values as original
>>> df.head(10)
data1 data2
0 -0.113909 3.625936
1 -2.795349 -1.362933
2 -3.750103 2.686047
3 3.286711 -2.937002
4 -0.279161 -2.255135
5 -0.394181 3.937575
6 -1.166115 0.776880
7 -2.750386 0.681216
8 1.375598 -1.070675
9 -0.871180 -0.122937
df[(df < 0.5) & (df > -0.5)] = np.nan
# Show df with NaN when between -0.5 and 0.5
>>> df.head(10)
data1 data2
0 NaN 3.625936
1 -2.795349 -1.362933
2 -3.750103 2.686047
3 3.286711 -2.937002
4 NaN -2.255135
5 NaN 3.937575
6 -1.166115 0.776880
7 -2.750386 0.681216
8 1.375598 -1.070675
9 -0.871180 NaN