【问题标题】:How to extract value from an array based on condition in pandas or numpy?如何根据 pandas 或 numpy 中的条件从数组中提取值?
【发布时间】:2019-12-21 21:04:47
【问题描述】:

我有以下值的数据框

        Bird    Color
   0    Parrot  ['Light_Blue','Green','Dark_Blue']
   1    Eagle   ['Sky_Blue','Black','White', 'Yellow','Gray']
   2    Seagull ['White','Jet_Blue','Pink', 'Tan','Brown', 'Purple']

我想创建一个名为“No Blue”的列,它只会列出其中不包含“Blue”一词的数组元素。

像这样:

    Bird    Color                                                No Blue
0   Parrot  ['Light_Blue','Green','Dark_Blue']                   ['Green']
1   Eagle   ['Sky_Blue','Black','White', 'Yellow','Gray']        ['Black', 'White', 'Yellow', 'Gray']
2   Seagull ['White','Jet_Blue','Pink', 'Tan','Brown', 'Purple'] ['White', 'Pink', 'Tan', 'Brown', 'Purple']

这是我最接近解决方案的事情

>>> Eagle = ['Sky_Blue','Black','White', 'Yellow','Gray']
>>> matching = [x for x in Eagle if "Blue" not in x]
>>> matching
['Black', 'White', 'Yellow', 'Gray']

【问题讨论】:

  • 我想知道如何使用str.extractstr.replace 等来实现
  • 由于您在每一行中迭代一个列表,我认为传递 .apply(lambda...) 更有效

标签: python pandas numpy


【解决方案1】:

我会使用这个代码:

df["noBlue"]=df.Color.apply(lambda x: [v for v in x if "Blue" not in v])

【讨论】:

    【解决方案2】:

    我正在从命令中运行它,所以请露出我的指纹!:

    import pandas as pd
    a = {'Bird':['Parrot','Eagle','Seagull'],'Color':[['Light_Blue','Green','Dark_Blue'],['Sky_Blue','Black','White', 'Yellow','Gray'],['White','Jet_Blue','Pink', 'Tan','Brown', 'Purple']]}
    df = pd.DataFrame(a)
    print(df)
    

    我在这里匹配你的结果:

          Bird                                        Color
    0   Parrot               [Light_Blue, Green, Dark_Blue]
    1    Eagle       [Sky_Blue, Black, White, Yellow, Gray]
    2  Seagull  [White, Jet_Blue, Pink, Tan, Brown, Purple]
    

    这将根据条件创建您的新列:

    df["Not_Blue"] = df['Color'].apply(lambda x: [a for a in x if "Blue" not in a])
    print(df)
    

    输出:

          Bird                                        Color                           Color_Not_Blue
    0   Parrot               [Light_Blue, Green, Dark_Blue]                            [Green]
    1    Eagle       [Sky_Blue, Black, White, Yellow, Gray]       [Black, White, Yellow, Gray]
    2  Seagull  [White, Jet_Blue, Pink, Tan, Brown, Purple]  [White, Pink, Tan, Brown, Purple]
    

    【讨论】:

      【解决方案3】:

      试试这个:

      >>> df['color'].str.replace(r'\w+_Blue\b', "")
      0                                 ['','Green','']
      1           ['','Black','White', 'Yellow','Gray']
      2    ['White','','Pink', 'Tan','Brown', 'Purple']
      

      出于个人好奇,我打开了另一个SO thread 以使用replace 获取它,如果您使用的是pandas 版本0.25,则得到以下解决方案。

      查看主题以获得其他解决方案..

       df['color'].str.replace(r'\w+_Blue\b', '').explode().loc[lambda x : x!=''].groupby(level=0).apply(list)
      

      【讨论】:

        猜你喜欢
        • 2021-11-28
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 2022-09-27
        • 2012-07-23
        • 2017-02-12
        • 2018-05-28
        • 2021-12-03
        相关资源
        最近更新 更多