pandas-where,mask

在这里插入图片描述
不符合条件的显示空值 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[ ]:




猜你喜欢

转载自blog.csdn.net/lildn/article/details/114704567