【问题标题】:Using Apply Map to Remove Unwanted Phrases from DF (Pandas, Python 3)使用 Apply Map 从 DF 中删除不需要的短语(Pandas,Python 3)
【发布时间】:2014-09-29 20:35:16
【问题描述】:

现在,我有一个这样的 DF

Words               Words1
Little Red         Red Apple
Cracker Barrel     Wood Grain
Far Away Man       Flat Rate Shipping

我想根据某些词不能同时出现在同一个短语中的特定条件从我的 DF 中删除单元格。

例如:从以下 DF 中删除单元格,其中“Flat”与“Shipping”在同一个短语中,并且“Far”与“Man”在同一个短语中。我一直在玩这样的东西,但它不起作用......

Words.where(Words.applymap(lambda x: 'Flat' and 'Shipping' in x))

有什么想法吗?

【问题讨论】:

    标签: python-3.x pandas


    【解决方案1】:

    “删除单元格”是什么意思?我认为您的意思是删除行对吗?那么这将是apply,因为您会按行考虑。

    In [8]: def pred(x):
        c1 = ('Far' in x[0]) and ('Man' in x[0])
        c2 = ('Flat' in x[1]) and ('Shipping' in x[1])
       ...:     return c1 and c2
    
    In [9]: df.apply(pred, axis=1)
    Out[9]: 
    0    False
    1    False
    2     True
    dtype: bool
    

    所以你可以删除那些符合你的条件的行

    In [10]: df[~df.apply(pred, axis=1)]
    Out[10]: 
                Words      Words1
    0      Little Red   Red Apple
    1  Cracker Barrel  Wood Grain
    

    str.match 方法与正则表达式一起使用可能会更快。

    【讨论】:

    • 不幸的是,我正在使用 Pandas,使用此方法会引发以下错误:IndexError: ('index out of bounds', 'occured at index 0')
    • 弄清楚它为什么会抛出那个错误——不幸的是这对我不起作用
    • DF = DF.applymap(lambda x: x if not '$' in str(x) else x.replace('$', ''))DF = DF.applymap(lambda x: x if not '%' in str(x) else x.replace('%', ''))
    猜你喜欢
    • 2014-11-21
    • 2022-12-04
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-09
    • 2022-01-15
    相关资源
    最近更新 更多