[英]How to read data from json file and convert it to csv using pandas?
[英]Read a CSV file with Json column using Pandas
我有一個包含幾個 JSON 列的 CSV 文件,我正在使用 python panda 讀取它。 示例文件數據如下所示:
12345,67890,{"key1":"value1","key2":"value2","key3":"value3"},abcdefgh,{"key4":"value4"}
12345,67890,NONE,abcdefgh,{"key4":"value4"}
我在讀取 CSV 時使用,
作為分隔符,但這會導致問題,因為 JSON 數據也包含,
並且最終該行未正確定界。
pd.read_csv('s3://bucket-name/file.csv', sep=",")
我還嘗試了另一個正則表達式[a-zA-Z0-9],|[}],
作為分隔符,但這會從列數據中刪除最后一個字符( , 之前,
1 個字符)。
如果我們不采用逗號后跟 json 元素,我們可以正確加載文件。
import pandas as pd
import io
input_csv = io.StringIO("""
12345, 67890,{"key1":"value1", "key2":"value2","key3":"value3"},abcdefgh,{"key4":"value4"}
12345,67890,NONE, "abcdefgh",{"key4":"value4"}
""")
df = pd.read_csv(input_csv, header=None,
sep=r',(?! ?\"\w+\"(?=:))', engine='python')
print(df.to_string())
---------------------------------------
0 1 2 3 4
0 12345 67890 {"key1":"value1", "key2":"value2","key3":"value3"} abcdefgh {"key4":"value4"}
1 12345 67890 NONE "abcdefgh" {"key4":"value4"}
",(?? ?"\w+"(:=,)) " g, 匹配字符? with index 4410 (2C16 or 548) literally (case sensitive) Negative Lookahead (?? :"\w+"(?=,)) Assert that the Regex below does not match matches the character with index 3210 (2016 or 408) literally (區分大小寫),在零到一次之間匹配前一個標記,盡可能多次,根據需要返回(貪婪)“匹配字符”與索引 3410(2216 或 428)字面(區分大小寫)\w 匹配任何單詞字符(相當於 [a-zA-Z0-9_])
- 在一次和無限次之間匹配前一個標記,盡可能多次,根據需要返回(貪婪)“匹配字符”與索引 3410(2216 或 428)字面(區分大小寫)Positive Lookahead (?=:) Assert that下面的正則表達式 matches: matches the character: with index 5810 (3A16 or 728) literally (case sensitive)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.