pandas-where,mask

本文介绍如何在数据分析中利用pandas的where和mask函数,将不符合条件的数据替换为NaN空值,以此进行数据筛选和清洗。
摘要由CSDN通过智能技术生成

在这里插入图片描述
不符合条件的显示空值 NaN

#!/usr/bin/env python
# coding: utf-8

# # 第一课 数据分析工具Pandas高阶
# ## 第五节 where与mask函数

# In[1]:


import pandas as pd
import numpy as np


# In[2]:
s = pd.Series(np.arange(5), 
              index=['a', 'b', 'c', 'd', 'e'])
# In[3]:
s
# * 对比where与过滤操作
# In[4]:
s[s > 0]
# In[5]:
# 使用where
s.where(s > 0)
# In[6]:
# 使用other参数
s.where(s > 0, -1)
# In[7]:
df = pd.DataFrame({'col1': [1, 2, 3, 4], 
                   'col2': ['a', 'b', 'f', 'n'],
                   'col3': ['a', 'n', 'c', 'n']})
# In[8]:
df
# In[9]:
# 结合isin()
vals = {'col1': [1, 3],
         'col2': ['a', 'b']}
df.where(df.isin(vals), other='-1')

	col1	col2	col3
0	1	    a	-1
1	-1  	b	-1
2	3	  -1	-1
3	-1	  -1	-1

# * mask函数
# In[10]:
s
# In[11]:
cond = s>0
# In[12]:
s.where(cond)
a    NaN
b    1.0
c    2.0
d    3.0
e    4.0

dtype: float64
# In[15]:
s.mask(cond)
# In[16]:
s.mask(~cond)
# In[ ]:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值