我在 CSV 檔案中有一個包含鍵值對的資料集,看起來類似于:
"1, {""key"": ""construction_year"", ""value"": 1900}, {""key"": ""available_date"", ""value"": ""Vereinbarung""}"
"2, {""key"": ""available_date"", ""value"": ""01.04.2022""}, {""key"": ""useful_area"", ""value"": 60.0}"
"3, {""key"": ""construction_year"", ""value"": 2020}, {""key"": ""available_date"", ""value"": ""sofort""}"
"4, {""key"": ""available_date"", ""value"": ""Vereinbarung""}, {""key"": ""wheelchair_accessible"", ""value"": true}"
我的預期輸出如下:
id construction_year available_date useful_area wheelchair_accessible
1 1900 Vereinbarung nan nan
2 nan 01.04.202 60.0 nan
3 2020 sofort nan nan
4 nan Vereinbarung nan true
我已經嘗試將這些資料轉換為dict使用json.loads然后決議它。當我可以確保所有行都以 JSON 樣式完美格式化時,此方法適用于小規模。
但是,當我嘗試使用具有 200'000 個觀察值json.loads的 alist時,我總是會遇到一些錯誤,因為并非所有行都采用正確的 JSON 格式。例如,有時“鍵”中缺少“值”,有時會出現{錯誤的位置,因此json.loads導致以下錯誤:JSONDecodeError: Expecting property name enclosed in double quotes
我已經嘗試將整個資料修復為 JSON 友好格式,但這似乎是不可能的,我收到的資料集格式很糟糕而且非常混亂。
所以我想知道是否有人可以想出一個函式,它允許我將鍵值對拆分為單獨的列,而不必使用json.loads.
提前致謝。
uj5u.com熱心網友回復:
看起來有人抓取了 JavaScript 代碼并保存為 CSV 字串。
"1, {""key"": ""construction_year"", ""value"": 1900}, {""key"": ""available_date"", ""value"": ""Vereinbarung""}"
它需要將 CSV 字串轉換回普通字串,然后再對其進行決議。
或者它需要逐行更改文本以更正 JSON 資料
[1, {"key": "construction_year", "value": 1900}, {"key": "available_date", "value": "Vereinbarung"}]
可以轉換為 3 列。
稍后您可以將字典轉換為一本字典
[1, {'construction_year': 1900, 'available_date': 'Vereinbarung'}]
可以使用pandas和轉換為列.apply(pd.Series)
我text用作字串,但您可以從檔案中讀取它
text = '''"1, {""key"": ""construction_year"", ""value"": 1900}, {""key"": ""available_date"", ""value"": ""Vereinbarung""}"
"2, {""key"": ""available_date"", ""value"": ""01.04.2022""}, {""key"": ""useful_area"", ""value"": 60.0}"
"3, {""key"": ""construction_year"", ""value"": 2020}, {""key"": ""available_date"", ""value"": ""sofort""}"
"4, {""key"": ""available_date"", ""value"": ""Vereinbarung""}, {""key"": ""wheelchair_accessible"", ""value"": true}"
'''
import pandas as pd
#text = open('data.csv').read()
rows = []
for line in text.splitlines():
line = line.replace('""', '"')
line = '[' line[1:-1] ']'
line = json.loads(line)
item = {}
for d in line[1:]:
key = d['key']
val = d['value']
item[key] = val
rows.append( [line[0], item] )
df = pd.DataFrame(rows, columns=['id', 'data'])
# convert dictionaries to columns
df = df.join(df['data'].apply(pd.Series))
# remove column with dictionaries
del df['data']
print(df.to_string())
結果:
id construction_year available_date useful_area wheelchair_accessible
0 1 1900.0 Vereinbarung NaN NaN
1 2 NaN 01.04.2022 60.0 NaN
2 3 2020.0 sofort NaN NaN
3 4 NaN Vereinbarung NaN True
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/461367.html
