【问题标题】:How to discard records containg offer_price greater than original price如何丢弃包含offer_price大于原始价格的记录
【发布时间】:2019-11-30 12:00:08
【问题描述】:

csv 文件包含许多属性。我必须删除高于原价的 offer_price。 价格列按行包含以下内容。以下是五行。如何在python中做到这一点

{'offer_price': {'currency': 'GBP', 'value': 25.0}, 'regular_price': {'currency': 'GBP', 'value': 25.0}}
{'offer_price': {'currency': 'GBP', 'value': 20.0}, 'regular_price': {'currency': 'GBP', 'value': 20.0}}
{'offer_price': {'currency': 'GBP', 'value': 18.0}, 'regular_price': {'currency': 'GBP', 'value': 18.0}}
{'offer_price': {'currency': 'GBP', 'value': 30.0}, 'regular_price': {'currency': 'GBP', 'value': 30.0}}
{'offer_price': {'currency': 'GBP', 'value': 35.0}, 'regular_price': {'currency': 'GBP', 'value': 35.0}}

名称:价格,数据类型:int64

【问题讨论】:

    标签: python-3.x pandas data-science


    【解决方案1】:

    boolean indexing 与通过dicts 的键过滤值一起使用,.get 更通用-如果缺少某些键也可以:

    mask = (df['price'].map(lambda x: x.get('offer_price').get('value') < 
                                      x.get('regular_price').get('value')))
    

    或者如果 dict 中的每个键始终存在,则可以使用:

    mask = df['price'].map(lambda x: x['offer_price']['value'] < x['regular_price']['value'])
    

    df1 = df[mask]
    

    【讨论】:

    • 我收到错误,因为 AttributeError: 'str' object has no attribute 'get'
    • 通过应用第二个建议 TypeError: string indices must be integers
    • @KalyanMohanty - 在我将字符串转换为字典的解决方案之前使用 import astdf['price'] = df['price'].apply(ast.literal_eval)
    猜你喜欢
    • 1970-01-01
    • 2010-09-17
    • 2019-01-15
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 2011-10-04
    • 2011-06-02
    相关资源
    最近更新 更多