Pandas是基于NumPy 的一种工具,该工具是为了解决数据分析任务而创建的。Pandas 纳入了大量库和一些标准的数据模型,提供了高效地操作大型数据集所需的工具。Pandas提供了大量能使我们快速便捷地处理数据的函数和方法。你很快就会发现,它是使Python成为强大而高效的数据分析环境的重要因素之一。本文主要介绍一下Pandas中pandas.DataFrame.mask方法的使用。

DataFrame.mask(self, cond, other=nan, inplace=False, axis=None, level=None, errors='raise', try_cast=False) [source]

替换条件为True的值。

参数:       

condboolSeries/DataFrame,类似于数组或callable

如果condFalse,请保留原始值。如果为True

则用other中的相应值替换。如果cond是callable,

则它是在Series/DataFrame上计算的,

并且应返回布尔Series/DataFrame或数组。

可调用对象不得更改输入Series/DataFrame

(尽管pandas不会对其进行检查)。

otherscalarSeries/DataFrame或callable

condTrue的条目将替换为other的相应值。

如果other是callable,

则在Series/DataFrame上对其进行计算,

并应返回scalarSeries/DataFrame

可调用对象不得更改输入Series/DataFrame

(尽管pandas不会对其进行检查)。

inplace: 布尔值,默认为False

是否对数据执行适当的操作。

axisint,默认值None

对齐轴(如果需要)。

levelint,默认值None

对齐级别(如果需要)。

errorsstr{'raise','ignore'},默认值'raise'

请注意,当前此参数不会影响结果,

并且始终会强制转换为合适的dtype

1) 'raise':允许引发异常。

2) 'ignore':抑制异常。错误时返回原始对象。

try_castbool,默认为False

尝试将结果转换回输入类型(如果可能)。

返回:

与调用者类型相同

Notes

mask方法是if-then惯用语的一种应用。对于在主叫DataFrame的每个元素中,如果condFalse的元素被使用; 否则,将使用DataFrame中的相应元素 other。

的签名DataFrame.where()不同于 numpy.where()df1.where(m, df2)大致相当于np.where(m, df1, df2)

有关更多详细信息和示例,请参见indexing中的mask文档 。

例子

s = pd.Series(range(5))
s.where(s > 0)
0 NaN
1 1.0
2 2.0
3 3.0
4 4.0
dtype: float64
s.mask(s > 0)
0 0.0
1 NaN
2 NaN
3 NaN
4 NaN
dtype: float64
s.where(s > 1, 10)
0 10
1 10
2 2
3 3
4 4
dtype: int64
df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
df
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
m = df % 3 == 0
df.where(m, -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

推荐文档

相关文档

大家感兴趣的内容

随机列表