簡體   English   中英

pandas dataframe as json 文件使用索引值

[英]pandas dataframe as as json file using index value

我有一個由 groupby 創建的 pandas 數據幀,如下所示: airbus_df.groupby(['mfr']).apply(lambda row: row.to_json(orient='records')).to_frame() output 看起來像:

         0
mfr 
AIRBUS  [{"mfr mdl code":"3940005","icao":"A00C7A","se...
AIRBUS CANADA LTD PTNRSP    [{"mfr mdl code":"1400010","icao":"A062EC","se...
AIRBUS HELICOPTERS DEUTSCHLAND  [{"mfr mdl code":"5620040","icao":"A32422","se...
AIRBUS HELICOPTERS INC  [{"mfr mdl code":"1145005","icao":"A1F846","se...
AIRBUS INDUSTRIE    [{"mfr mdl code":"3930402","icao":"A009A4","se...
AIRBUS SAS  [{"mfr mdl code":"3940312","icao":"A3AD89","se

我想為每個“制造商”創建一個 json 文件。 如何使用索引名稱另存為 json。

df_t.index:
Index(['AIRBUS','AIRBUS CANADA LTD PTNRSP'...])

您可以按系列循環並通過索引值中的鍵將json寫入文件:

import json

for k,v in airbus_df.groupby('mfr').apply(lambda row:row.to_json(orient='records')).items():
        with open(f"{k}.json", 'w') as f: 
            json.dump(v, f)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM