我有一個df
clearance_info
4431,by category 2,2022-02-03
4231,by category 1,2022-02-03
4331,by category 3,2022-02-03
4431,by category 4,2022-02-03
如何將其轉換為
clearance_info
{"price": 4431 ,"category" : "by category 2","timestamp" : "2022-02-03"}
{"price": 4231 ,"category" : "by category 1","timestamp" : "2022-02-03"}
{"price": 4331 ,"category" : "by category 3","timestamp" : "2022-02-03"}
{"price": 4431 ,"category" : "by category 4","timestamp" : "2022-02-03"}
嘗試使用 orient split 但沒有按預期作業。請提出建議。
僅當存在單獨的列時才提供東方幫助,我希望這些列像提到的那樣固定。
uj5u.com熱心網友回復:
to_dict和orient="records"
cols = dict(enumerate(['price', 'category', 'timestamp']))
df.assign(
clearance_info=
df.clearance_info.str
.split(',', expand=True)
.rename(columns=cols)
.to_dict('records')
)
clearance_info
0 {'price': '4431', 'category': 'by category 2',...
1 {'price': '4231', 'category': 'by category 1',...
2 {'price': '4331', 'category': 'by category 3',...
3 {'price': '4431', 'category': 'by category 4',...
如果你想讓這個堅持df
df = df.assign(
clearance_info=
df.clearance_info.str
.split(',', expand=True)
.rename(columns=cols)
.to_dict('records')
)
uj5u.com熱心網友回復:
你可以試試:
df[['price', 'category','timestamp']] = df['clearance_info'].str.split(',',expand=True,n=3)
df['price'] = df['price'].astype(int)
df['clearance_info'] = df[['price', 'category','timestamp']].apply(lambda row: row.to_json(), axis=1)
df.drop(['price', 'category','timestamp'], axis=1, inplace=True)
輸出:
clearance_info
0 {"price":4431,"category":"by category 2","time...
1 {"price":4231,"category":"by category 1","time...
2 {"price":4331,"category":"by category 3","time...
3 {"price":4431,"category":"by category 4","time...
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/456645.html
上一篇:創建資料框組合并保留唯一的列值
下一篇:熊貓與第二個資料幀的平均值合并
