代码之家  ›  专栏  ›  技术社区  ›  Sudhi

基于dataframe中字符串列表的另一列获取列值

  •  3
  • Sudhi  · 技术社区  · 6 年前

    link . 但对于我下面给出的例子,它不起作用。 我尝试了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 作为我的答案。请告诉我我在这里犯了什么错误。

    2 回复  |  直到 6 年前
        1
  •  3
  •   jezrael    6 年前

    我相信你需要 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
    
        2
  •  1
  •   Mohit Motwani    6 年前

    df.loc[df['Item'].str.contains('Phone'), ['RelatedItem',  'CountinInventory']]
    

    too many indexers 是因为df.loc[]需要一个带有标签的标签、列表或切片对象数组。但是你已经给了一系列的标签。