python - 如何处理列中的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
解决方案
用一个lambda function
和Series.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)
推荐阅读
- python - 如何使用 Django 将 CSRF 令牌发送到 ajax 请求?
- c++ - 如何在给定此类信息的情况下打印 c++ 函数参数的内容
- c++ - 使用 Clion IDE 编译 OpenCV 项目失败
- python - 将 matplotlib 图转换为散景时间线图?
- ecmascript-6 - “不能在模块外使用 import 语句” - React 的危险系统
- html - Bootstrap:响应式卡片
- javascript - 如果 async/await 只是它们的包装器,为什么它比线程执行得更好?
- javascript - 如何将子程序放入 VUE 方法中
- coreml - 在第 0 行创建空的 ML 特征列
- java - 为什么即使我在 String 数组的范围内,我也会收到 StringOutOfBoundsException?