python pandas dataFrame 创建多列值的单个 json 列

标签 python json pandas

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

假设以下数据帧:
示例:

| -   | 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 类型)?

最佳答案

您可以使用 applyto_json , 最后通过 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 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44413682/

相关文章:

python - 将纪元转换为日期时间格式 python - typeerror

python - 使用 Pandas-Bokeh 绘制数据框时如何合并子图选项?

python - 修补父类

python - 我怎样才能包含多个项目的 "unwrap"列?

java - 使用gson库将Json反序列化为java类

c# - 使用 JSON.NET 反序列化值为字段名称的 JSON

python - 我们如何在 Flask 中使用参数从另一条路由调用一条路由?

python - 使用 kwargs 时如何转义 Python format() 中的冒号?

javascript - 将 JSON 映射到 backbone.js 集合

python - 导入 pandas.plotting 的问题