首页 > 解决方案 > 根据熊猫数据框中字符串列表的另一列获取列值

问题描述

我试过链接。但它不适用于我下面给出的示例。我尝试了 loc[0] 的输出。我试过.item()。但这些都没有帮助我。

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

我有这些数据,当我喂食时Phone,我需要以Phone cover价值CountinInventory作为我的答案。请告知我在这里犯了什么错误。

标签: pythonpython-3.xpandasmultiple-columns

解决方案


我相信你需要str删除第一个和最后一个[]或使用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

如果没有缺失值是可能的使用list comprehension,如果大数据更快:

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]

最后选择多列使用list

df3 = df2.loc[mask, ['RelatedItem', 'CountinInventory']]
print (df3)
     RelatedItem CountinInventory
0  [Phone cover]               20

推荐阅读