pandas中的 where 和mask方法

where

  • 表示不满足条件的,被设置为指定值

mask

  • 与where相反,满足条件的数据,被设置为指定值

示例代码:

import pandas as pd
import numpy as np

# 生成数据:
df = pd.DataFrame(np.arange(15).reshape((5, 3)))
# df>:
        0	1	2
0	0	1	2
1	3	4	5
2	6	7	8
3	9	10	11
4	12	13	14


# where,使得大于10的数设置为-1
df.where(df<=10, -1)  # 大于10,表示不满足 ***<=10*** 条件的被设置为10,此处要注意
# 输出:
        0	1	2
0	0	1	2
1	3	4	5
2	6	7	8
3	9	10	-1
4	-1	-1	-1

# mask,是满足条件的设置为指定值
# 输出:
        0	1	2
0	0	1	2
1	3	4	5
2	6	7	8
3	9	10	-1
4	-1	-1	-1

可以看到,mask比where更容易理解,根据个人爱好使用

原文地址:https://www.cnblogs.com/jaysonteng/p/13321884.html