官网查看
pd.where()
DataFrame.where(cond, other=nan, inplace=False, axis=None, level=None, errors=‘raise’, try_cast=False, raise_on_error=None)
pd.mask()
np.where()
numpy.where(condition[, x, y])
pd.query()
注意****
df.where(m, -df) == np.where(m, df, -df)
df.where(m, -df) == df.mask(~m, -df)
df1.where(m, df2) 等价于 np.where(m, df1, df2).
栗子:
df = pd.DataFrame(np.arange(10).reshape(-1, 2), columns=['A', 'B'])
print(df)
print('***'*5)
print(df.where(df>2,-df))
结果:
A B
0 0 1
1 2 3
2 4 5
3 6 7
4 8 9
********
A B
0 0 -1
1 -2 3
2 4 5
3 6 7
4 8 9
(2)pd.query()
DataFrame.query(expr, inplace=False, **kwargs)
让括号里面的表达式更加简单
栗子:
df = pd.DataFrame(np.random.randn(10, 2), columns=list('ab'))
print(df.query('a > b'))#两者是等价的
print(df[df.a > df.b] )
结果:
a b
0 0.203618 0.197262
4 0.808955 -1.582884
5 1.015357 -1.253568
6 1.585411 -1.386132
7 0.267986 -0.285372
8 0.429625 -0.116630
9 1.117835 -0.435331
a b
0 0.203618 0.197262
4 0.808955 -1.582884
5 1.015357 -1.253568
6 1.585411 -1.386132
7 0.267986 -0.285372
8 0.429625 -0.116630
9 1.117835 -0.435331