其他分享
首页 > 其他分享> > df.where的用法总结

df.where的用法总结

作者:互联网

1、pd.Series( ).where( cond ) 可以过滤不满足cond的值并赋予NaN空值

s = pd.Series(range(5))
s.where(s > 0)
0    NaN
1    1.0
2    2.0
3    3.0
4    4.0

2、pd.Series( ).mask(cond) 使用时,结果与where相反

s.mask(s > 0)
0    0.0
1    NaN
2    NaN
3    NaN
4    NaN

3、赋予other 值得用法

s.where(s > 1, 10)   #cond = s > 1,other = 10
0    10.0
1    10.0
2    2.0
3    3.0
4    4.0

4、df.where从主体df出发,True返回df 本身的值,否则返回other的值;np.where(cond,x,y),True返回x的值,False返回y的值

df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
m = df % 3 == 0
df.where(m, -df)   #cond = m,other = -df
   A  B
0  0 -1
1 -2  3
2 -4 -5
3  6 -7
4 -8  9
df.where(m, -df) == np.where(m, df, -df)
      A     B
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True
df.where(m, -df) == df.mask(~m, -df)
      A     B
0  True  True
1  True  True
2  True  True
3  True  True
4  True  True

去掉特定的某行某列:

df.where(df !=N).dropna(axis = 1)

参考资料:

https://blog.csdn.net/brucewong0516/article/details/80226990

标签:df,where,NaN,用法,other,cond,True
来源: https://www.cnblogs.com/yuyanc/p/16434531.html