Python 3.9.5/Pandas 1.1.3
我一直在使用Pandas從csv檔案中創建JSON檔案--JSON檔案中的鍵名是由csv檔案中的頭名稱生成的。 我遇到了一個問題,我必須多次使用相同的鍵名(在嵌套物件中),但我不能在 csv 檔案中使用兩個相同名稱的頭。
例子:
到目前為止,我的 csv 檔案將是 4 列。id, data, type, location。 我需要從這些東西到一個JSON物件的檔案(包括一個嵌套物件),并使用以下代碼完成:
import pandas as pd
import json
import os
csv = "/Users/me/file.csv"。
csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
csv_file['org'] = csv_file[['data', 'type']] 。 apply(lambda s: s.to_dict(), axis=1)
csv_file[['id', 'org']].to_json("file。 json", orient="records", lines=True, date_format="iso", double_precision=10, force_ascii=True, date_unit="ms", default_handler=None)
假設我在csv檔案中有一行資料,其值分別為1、ABC、XYZ和123,上述代碼將創建一個有此物件的json檔案:
{
"id": 1,
"org":{
"data":"ABC"。
"type":"XYZ"。
},
"位置":"123"
但是今天我收到了一個新的csv檔案,其中有6個列--和上面一樣的4個,加上兩個新的列,叫做data1和type1,它代表org_2。 我需要JSON檔案中這些值的鍵名也是data和type,但是我不能將csv檔案中的列命名為這個名字,因為已經有了這些名字的列。
所以我需要的是,假設6個列的值是1, ABC, XYZ, 123, Foo和Bar,創建的檔案中的JSON物件應該是這樣的:
{
"id":1。
"org":{
"data":"ABC"。
"type":"XYZ"。
},
"location":"123"。
"org_2":{
"data":"Foo"。
"type":"Bar".
}
}
所以像這樣:
csv = "/Users/me/file.csv"/span>
csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
csv_file['org'] = csv_file[['data', 'type']] 。 apply(lambda s: s.to_dict(), axis=1)
csv_file['org_2'/span>] = csv_file[['data1'/span>, 'type1'/span>]]。 apply(lambda s: s.to_dict(), axis=1)
csv_file[['id', 'org', 'org_2']].to_json("file. json", orient="records", lines=True, date_format="iso", double_precision=10, force_ascii=True, date_unit="ms", default_handler=None)
當然,上面的內容將創建名為data1和type1的鍵,而我需要它們只是data和type。
uj5u.com熱心網友回復:
你需要在應用前重命名這些列:
csv_file['org_2'] = csv_file[['data1', 'type1']] 。 set_axis(['data', 'type'], axis=1) 。 apply(lambda s: s.to_dict(), axis=1)
uj5u.com熱心網友回復:
我們可以使用rename函式,它回傳一個新的dataframe,其中有重命名的列,并在上面應用lambda函式。
csv = "/Users/me/file.csv"/span>
csv_file = pd.read_csv(csv, sep=",", header=0, index_col=False)
csv_file['org'] = csv_file[['data', 'type']] 。 apply(lambda s: s.to_dict(), axis=1)
csv_file['org_2'/span>] = csv_file[['data1'/span>, 'type1'/span>]]。 rename(['data1' : 'data', 'type1':'type'] )。) apply(lambda s: s.to_dict(), axis=1)
csv_file[['id', 'org', 'org_2']].to_json("file. json", orient="records", lines=True, date_format="iso", double_precision=10, force_ascii=True, date_unit="ms", default_handler=None)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/310237.html
標籤:
