PandasDataFrame-将列转换为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"}

...

回答

你可以aggdictaxis=1

对于字典:

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'}


以上是PandasDataFrame-将列转换为JSON并添加为新列的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>