簡體   English   中英

Python - Function 用於將鍵值對解析為 DataFrame 列

[英]Python - Function for parsing key-value pairs into DataFrame columns

我在 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}"

我預期的 output 如下:

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

我已經嘗試使用json.loads將此數據轉換為dict ,然后對其進行解析。 當我可以確保所有行都以 JSON 樣式完美格式化時,此方法適用於小規模。

但是,當我嘗試在包含 200'000 個觀察值的list中使用json.loads時,我總是會遇到一些錯誤,因為並非所有行都采用正確的 JSON 格式。 例如,有時“鍵”中缺少“值”,有時{放在錯誤的位置,因此json.loads會導致以下錯誤: JSONDecodeError: Expecting property name enclosed in double quotes

幾天來我一直在嘗試將整個數據修復為 JSON 友好格式,但這似乎是不可能的,我收到的數據集格式很糟糕而且非常混亂。

所以我想知道是否有人可以想出一個 function 允許我將鍵值對拆分成單獨的列,而不必使用json.loads

提前致謝。

看起來有人抓取了 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

暫無
暫無

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

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