[英]Python Pandas Data Frame search
I have code here where I'm searching through a series on a pandas dataframe. 我在这里有代码,在其中搜索熊猫数据框上的一系列代码。
df[(df['SlyWeekofFiscalYear']==wk) &
(df['IB']==bnd) &
(df['slyfiscalyear']==yr)]
['Wholesale'].sum()
It's in a function that passes a kwarg bnd=None
. 它在传递kwarg bnd=None
的函数中。 Is there a way to disregard the 2nd line of code if bnd=None
? 如果bnd=None
有没有办法忽略第二行代码?
Currently I have a long if statement but I'd like to tidy up the code if possible. 目前,我有一个很长的if语句,但是如果可能的话,我想整理一下代码。
You can change the second line to ((bnd is None) | (df['IB'] == bnd))
. 您可以将第二行更改为((bnd is None) | (df['IB'] == bnd))
。 If bnd
is None, this produces an all true Series, and since you have &
operators, it will have no effect on the result. 如果bnd
为None,这将产生一个全真数列,并且由于您具有&
运算符,因此对结果没有影响。
You could try a ternary statement: 您可以尝试三元声明:
(df['IB'] == bnd if bnd is not None else True)
The scalar value True
should be broadcast properly to a vector of the right length. 标量值True
应该正确地广播到正确长度的向量。
Have you tried replacing the second line with some thing that's always true
if bnd=None
? 如果bnd=None
,您是否尝试用总是true
东西替换第二行?
Somelike: 有点像:
((df['IB']==bnd) | (bnd is None))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.