[英]Using multiple loc()
Im trying to use multiple loc() on the below table but unfortunately the code is giving me an error stating:我试图在下表中使用多个 loc() 但不幸的是代码给了我一个错误说明:
ValueError: The truth value of a DataFrame is ambiguous. ValueError:DataFrame 的真值不明确。 Use a.empty, a.bool(), a.item(), a.any() or a.all().使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
my df is the following:我的 df 如下:
REFERENCE PERIOD QTY PRICE
abc123 Jan-20 20 21.2
abc123 Feb-20 -40 22.3
abc123 Mar-20 20 22.9
cde456 Aug-20 -10 18.7
cde456 Sep-20 20 19.4
cde456 Jan-20 -10 19.93
The code giving me an error should ideally return a subset of the table:理想情况下,给我一个错误的代码应该返回表的一个子集:
dfa = df.loc[df['PERIOD'].str.contains(pat='JAN')] and df.loc[df['REFERENCE'].str.contains(pat='abc')]
Any ideas how what im doing wrong to use 2 .loc functions in the same string?任何想法在同一字符串中使用 2 个 .loc 函数时我做错了什么?
Thx谢谢
Try single loc
with boolean operator:使用布尔运算符尝试单个loc
:
df.loc[df['PERIOD'].str.contains('JAN') &
df['REFERENCE'].str.contains('A')]
You can give two conditions by separating them with &
.你可以用&
分隔两个条件。 Therefore, you don't need to use two .loc
.因此,您不需要使用两个.loc
。
With .loc
使用.loc
df.loc[(df['PERIOD'].str.contains('Jan')) & (df['REFERENCE'].str.contains('abc'))]
Or或者
Without .loc
没有.loc
df[(df['PERIOD'].str.contains('Jan')) & (df['REFERENCE'].str.contains('abc'))]
Output:输出:
REFERENCE PERIOD QTY PRICE
0 abc123 Jan-20 20 21.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.