gpt4 book ai didi

python - 寻找一种更有效的方法来从数据框列中的字典创建新列

转载 作者:太空宇宙 更新时间:2023-11-04 02:17:28 25 4
gpt4 key购买 nike

我想在数据框中重组我的数据:

df = pd.DataFrame({'order_id': ['A', 'B'],
'address': [{'city': "NY", 'latitude': 2.12, 'longitude' : 3.12,'country_code' : "US"},
{'city': "KL", 'latitude': 12.12, 'longitude' : 23.12,'country_code' : "MY"}]},
columns= ['order_id', 'address'])

df
order_id address
0 A {'city': 'NY', 'latitude': 2.12, 'longitude': 3.12, 'country_code': 'US'}
1 B {'city': 'KL', 'latitude': 12.12, 'longitude': 23.12, 'country_code': 'MY'}

我需要的是:

  order_id address_city address_country_code
0 A NY US
1 B KL MY

这是我的工作代码:

new_cols = ['city', 'country_code']
for col in new_cols:
df['address_{}'.format(col)] = \
df['address'].map(lambda x: np.nan if pd.isnull(x) else x[col])
df.drop(['address'], axis=1)

如何优化代码以使其更高效?

最佳答案

您可以使用 zip 解压缩城市和国家/地区和列表理解。

cities, country_codes = zip(*[(d['city'], d['country_code']) for d in df['address']])

>>> pd.DataFrame({
'order_id': df['order_id'].values,
'address_city': cities,
'address_country_code': country_codes})[['order_id', 'address_city', 'address_country_code']]
order_id address_city address_country_code
0 A NY US
1 B KL MY

关于python - 寻找一种更有效的方法来从数据框列中的字典创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52335184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com