首页 > 解决方案 > 如何处理列中的unicode值dict

问题描述

我在 df 中有一个列(“折扣”),每个值都采用其格式:

{u'customer': u'xdawd', u'end': None, u'coupon': {u'object': u'coupon', u'name': u'Black Friday', u'percent_off': None, u'created': 213213, u'times_redeemed': 10, u'amount_off': 2500, u'currency': u'gbp', u'object': u'discount', u'start': 1543327380, u'subscription': u'uiodsjciosdj'}

我想在一个新列中返回 percent_off 值或 amount_off 值(两者中只出现一个),所以我必须得到它的值不是 None 的那个。

只是它在 excel 中的一个示例: https ://i.imgur.com/Dt2fj8i.png

标签: pythonpandasunicodeapply

解决方案


用一个lambda functionSeries.apply

df['discount'].apply(lambda x: x['coupon'].get('percent_off') or x['coupon'].get('amount_off'))

[出去]

0    2500
Name: discount, dtype: int64

或者,如果您希望按照@lenz 的建议更明确:

def extract_discount(x):
    return x['coupon'].get('percent_off') or x['coupon'].get('amount_off') 

df['discount'].apply(extract_discount)

推荐阅读