Get Column Value Based On Another Column With List Of Strings In Pandas Dataframe
I tried the link. But it doesnt work for my example given below. I tried the loc[0] for the output. I tried .item(). But none of these help me. >>> df2 = pd.DataFrame({ '
Solution 1:
I believe you need str
for remove first and last []
or use str.strip
:
mask = df2['Item'].str[1:-1] == 'Phone'#alternative solution#mask = df2['Item'].str.strip('[]') == 'Phone'print (mask)
0True1False2False3False4False
Name: Item, dtype: bool
If no missing values is possible use list comprehension
, what is faster if large data:
mask = [x[1:-1] == 'Phone'for x in df2['Item']]
mask = [x.strip('[]') == 'Phone'for x in df2['Item']]
print (mask)
[True, False, False, False, False]
Last for select multiple columns use list
:
df3 = df2.loc[mask, ['RelatedItem', 'CountinInventory']]
print (df3)
RelatedItem CountinInventory
0 [Phone cover] 20
Solution 2:
You could also use:
df.loc[df['Item'].str.contains('Phone'), ['RelatedItem', 'CountinInventory']]
The error too many indexers
is because df.loc[] expects an array of labels, list or slice object with labels. But you have given a sequence of 'labels'.
Post a Comment for "Get Column Value Based On Another Column With List Of Strings In Pandas Dataframe"