Reputation: 37
Im trying to use multiple loc() on the below table but unfortunately the code is giving me an error stating:
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
my df is the following:
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?
Thx
Upvotes: 1
Views: 56
Reputation: 3594
You can give two conditions by separating them with &
. Therefore, you don't need to use two .loc
.
With .loc
df.loc[(df['PERIOD'].str.contains('Jan')) & (df['REFERENCE'].str.contains('abc'))]
Or
Without .loc
df[(df['PERIOD'].str.contains('Jan')) & (df['REFERENCE'].str.contains('abc'))]
Output:
REFERENCE PERIOD QTY PRICE
0 abc123 Jan-20 20 21.2
Upvotes: 0
Reputation: 153460
Try single loc
with boolean operator:
df.loc[df['PERIOD'].str.contains('JAN') &
df['REFERENCE'].str.contains('A')]
Upvotes: 2