python - Pandas DataFrame - 将列转换为 JSON 并添加为新列

考虑使用我从 11k 行大小的 MySQL 表中获得的以下 DataFrame:

col1 |  col2 | col3  | col4
-----------------------------
 cat | black | small | lovely
-----------------------------
 dog | white | medium| brave 
-----------------------------
mice | grey  | tinny | fast

...

我想将其动态转换为以下内容:

col1 |     newcol
------------------------------------------------------------
 cat | {"col2": "black", "col3": "small", "col4": "lovely"}
------------------------------------------------------------
 dog | {"col2": "white", "col3": "medium", "col4": "brave"}
------------------------------------------------------------
mice | {"col2": "grey", "col3": "tinny", "col4": "fast"}

...

最佳答案

您可以在 axis=1 上将 agg 用作 dict

对于字典:

out = df[['col1']].assign(new_col=df.iloc[:,1:].agg(dict,1))

对于 json:

out = df[['col1']].assign(new_col=df.iloc[:,1:].agg(pd.Series.to_json,1))

print(out)

   col1                                            new_col
0   cat  {'col2': 'black', 'col3': 'small', 'col4': 'lo...
1   dog  {'col2': 'white', 'col3': 'medium', 'col4': 'b...
2  mice  {'col2': 'grey', 'col3': 'tinny', 'col4': 'fast'}

https://stackoverflow.com/questions/65496242/

相关文章:

docker - Elastic search AccessDeniedException[/usr

c++ - 重构为枚举以枚举类阴影命名空间

amazon-web-services - `amplify push` 失败 - 属性 : Str

c# - 使用 MVVM 绑定(bind) : Property not found in Xama

mongodb - 如何在 NestJS (MongoDB) 中设置唯一复合索引

arrays - 检查列表和数组是否相等 F#

java - Java 是否根据结果假定类型?

python - Flask-SQLAlchemy: SAWarning: Identity map

c++ - 一个只接受枚举类型参数的模板类?

r - 如何在 R 中的数据框中重新编码数据