考虑使用我从 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/