Python Pandas 将多列合并成一个字典列 [英] Python Pandas merge multiple columns into a dictionary column

查看:211
本文介绍了Python Pandas 将多列合并成一个字典列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框 (df_full):

I have a dataframe (df_full) like so:

|cust_id|address    |store_id|email        |sales_channel|category|
-------------------------------------------------------------------
|1234567|123 Main St|10SjtT  |idk@gmail.com|ecom         |direct  |
|4567345|345 Main St|10SjtT  |101@gmail.com|instore      |direct  |
|1569457|876 Main St|51FstT  |404@gmail.com|ecom         |direct  |

我想将最后 4 个字段组合成一个元数据字段,它是一个像这样的字典:

and I would like to combine the last 4 fields into one metadata field that is a dictionary like so:

|cust_id|address    |metadata                                                                                     |
-------------------------------------------------------------------------------------------------------------------
|1234567|123 Main St|{'store_id':'10SjtT', 'email':'idk@gmail.com','sales_channel':'ecom', 'category':'direct'}   |
|4567345|345 Main St|{'store_id':'10SjtT', 'email':'101@gmail.com','sales_channel':'instore', 'category':'direct'}|
|1569457|876 Main St|{'store_id':'51FstT', 'email':'404@gmail.com','sales_channel':'ecom', 'category':'direct'}   |

这可能吗?我已经看到了一些关于堆栈溢出的解决方案,但没有一个解决将超过 2 个字段组合到字典字段中的问题.

is that possible? I've seen a few solutions around on stack overflow but none of them address combining more than 2 fields into a dictionary field.

推荐答案

使用 to_dict,

columns = ['store_id', 'email', 'sales_channel', 'category']
df['metadata'] = df[columns].to_dict(orient='records')

如果你想删除原始列,

And if you want to drop original columns,

df = df.drop(columns=columns)

这篇关于Python Pandas 将多列合并成一个字典列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆