简体   繁体   中英

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({ '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.

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

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM