使用
lambda
函数与
get
对于匹配值,如果字典带有键
id
否则返回默认值,此处
0
:
orders_df = pd.DataFrame({'customer':[{'id': 454543543533, 'email': 'fdgr@gmail.com'},
{'id': 437890767654, 'email': 'ereffewf@mail.com'},
{'email': 'ereffewf@mail.com'}]})
print (orders_df)
customer
0 {'id': 454543543533, 'email': 'fdgr@gmail.com'}
1 {'id': 437890767654, 'email': 'ereffewf@mail.c...
2 {'email': 'ereffewf@mail.com'}
orders_df['customer'] = orders_df['customer'].apply(lambda x: x.get('id', 0))
或:
orders_df['customer'] = [x.get('id', 0) for x in orders_df['customer']]
print (orders_df)
customer
0 454543543533
1 437890767654
2 0