python pandas dataFrame创建多列值的单个json列 [英] python pandas dataFrame create single json column of multiple columns value

查看:92
本文介绍了python pandas dataFrame创建多列值的单个json列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 python pandas dataFrame 中,我想创建多列值的单个 json 列.

In python pandas dataFrame i wanted create single json column of multiple columns value.

假设以下数据帧:
示例:

| -   | col1 | col2 | col3 | col4|
| 1   | abc  | def  | ghi  |  8  |
| 2   | xab  | xcd  | xef  |  9  |

这就是我想要的结果.

|     |col1 | json_col|br
|1    | abc |   {"col2":"def","col3":"ghi","col4":8}|
|2    | xab |   {"col2":"xcd","col3":"xef","col4":9}|

如何创建选定列的单列(json 类型)?

How can i create the single column(json type) of selected columns?

推荐答案

您可以使用 applyto_json,最后通过 drop:

You can use apply with to_json, last remove columns by drop:

cols = ['col2','col3','col4']
df['json_col'] = df[cols].apply(lambda x: x.to_json(), axis=1)
df = df.drop(cols, axis=1)
print (df)
   - col1                              json_col
0  1  abc  {"col2":"def","col3":"ghi","col4":8}
1  2  xab  {"col2":"xcd","col3":"xef","col4":9}

这篇关于python pandas dataFrame创建多列值的单个json列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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