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

posted @   C羽言  阅读(602)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示