pandas 相当于 np.where
pandas equivalent of np.where
np.where
具有矢量化 if/else 的语义(类似于 Apache Spark 的 when
/otherwise
DataFrame 方法)。我知道我可以在 pandas.Series
上使用 np.where
,但是 pandas
经常定义它自己的 API 来使用而不是原始的 numpy
函数,这通常更方便pd.Series
/pd.DataFrame
.
果然找到了pandas.DataFrame.where
。然而,乍一看,它具有完全不同的语义。我找不到使用 pandas where
:
重写 np.where
的最基本示例的方法
# df is pd.DataFrame
# how to write this using df.where?
df['C'] = np.where((df['A']<0) | (df['B']>0), df['A']+df['B'], df['A']/df['B'])
我是不是遗漏了什么明显的东西?或者 pandas' where
用于完全不同的用例,尽管与 np.where
同名?
尝试:
(df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
numpy
where
和 DataFrame
where
之间的区别在于,默认值由 DataFrame
提供,而 where
方法正在调用 (docs).
即
np.where(m, A, B)
大致相当于
A.where(m, B)
如果您想要使用 pandas 的类似呼叫签名,您可以利用 the way method calls work in Python:
pd.DataFrame.where(cond=(df['A'] < 0) | (df['B'] > 0), self=df['A'] + df['B'], other=df['A'] / df['B'])
或不带 kwargs(注意:参数的位置顺序与 numpy
where
argument order 不同):
pd.DataFrame.where(df['A'] + df['B'], (df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
我更喜欢使用 pandas' mask
over where
因为它不那么违反直觉(至少对我而言)。
(df['A']/df['B']).mask(df['A']<0) | (df['B']>0), df['A']+df['B'])
此处,在条件成立的地方添加列 A
和 B
,否则它们的比率保持不变。
np.where
具有矢量化 if/else 的语义(类似于 Apache Spark 的 when
/otherwise
DataFrame 方法)。我知道我可以在 pandas.Series
上使用 np.where
,但是 pandas
经常定义它自己的 API 来使用而不是原始的 numpy
函数,这通常更方便pd.Series
/pd.DataFrame
.
果然找到了pandas.DataFrame.where
。然而,乍一看,它具有完全不同的语义。我找不到使用 pandas where
:
np.where
的最基本示例的方法
# df is pd.DataFrame
# how to write this using df.where?
df['C'] = np.where((df['A']<0) | (df['B']>0), df['A']+df['B'], df['A']/df['B'])
我是不是遗漏了什么明显的东西?或者 pandas' where
用于完全不同的用例,尽管与 np.where
同名?
尝试:
(df['A'] + df['B']).where((df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
numpy
where
和 DataFrame
where
之间的区别在于,默认值由 DataFrame
提供,而 where
方法正在调用 (docs).
即
np.where(m, A, B)
大致相当于
A.where(m, B)
如果您想要使用 pandas 的类似呼叫签名,您可以利用 the way method calls work in Python:
pd.DataFrame.where(cond=(df['A'] < 0) | (df['B'] > 0), self=df['A'] + df['B'], other=df['A'] / df['B'])
或不带 kwargs(注意:参数的位置顺序与 numpy
where
argument order 不同):
pd.DataFrame.where(df['A'] + df['B'], (df['A'] < 0) | (df['B'] > 0), df['A'] / df['B'])
我更喜欢使用 pandas' mask
over where
因为它不那么违反直觉(至少对我而言)。
(df['A']/df['B']).mask(df['A']<0) | (df['B']>0), df['A']+df['B'])
此处,在条件成立的地方添加列 A
和 B
,否则它们的比率保持不变。