Reputation: 421
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({ 'Item':['[Phone]', '[Watch]', '[Pen]', '[Pencil]', '[Knife]'], 'RelatedItem': ['[Phone cover]', '[Watch strap]', '[Pen cap]', '[Pencil lead]', '[fork]'], 'CountinInventory':['20','50','40','80','90']})
>>> df2
Item RelatedItem CountinInventory
0 [Phone] [Phone cover] 20
1 [Watch] [Watch strap] 50
2 [Pen] [Pen cap] 40
3 [Pencil] [Pencil lead] 80
4 [Knife] [fork] 90
>>> df2.loc[df2['Item'] == 'Phone', 'RelatedItem']
Series([], Name: RelatedItem, dtype: object)
>>> df2.loc[df2['Item'] == 'Phone', 'RelatedItem', 'CountinInventory']
pandas.core.indexing.IndexingError: Too many indexers
I have this data where when I feed Phone
, I need to get Phone cover
along with the CountinInventory
value as my answer. Please advice what mistake am I doing here.
Upvotes: 3
Views: 7950
Reputation: 4792
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'.
Upvotes: 1
Reputation: 863281
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)
0 True
1 False
2 False
3 False
4 False
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
Upvotes: 3