我有需要讀取的 CSV 檔案,其中一些行讀得很好,但其他行看起來像這樣:
2022-10-04, "", some data in col3, moredata, "data in quotes, like the size for this thing is 23'' x \28" with this description, moredata
2022-10-05, "", some data in col3, moredata, "data in quotes, like the size for this thing is 23“ x \28" with this description, moredata
所以我無法解決的問題是:這是一個 CSV - 所以逗號是分隔符,它使用雙引號分隔符來表示其中包含多個逗號的值,這些逗號不應該被讀取為分隔符,好的,我想出了如何考慮到 pandas read_csv 選項中的這一點,
但是,在一些引號分隔的欄位中,當有以英寸為單位的數字時,它們使用全部 4 個:
轉義雙引號:\"
雙單引號:''
AND 左或右雙引號,例如:“ 未轉義的,我認為可能會被誤讀為引號分隔符,我不確定如何忽略它們。
我不知道如何讓 CSV 在 Pandas 或任何其他方法中正確讀取。有很多行資料使用這些左右雙引號而不轉義它們,所以如果一行看起來像:
something, "one value with 23'', 25\", 20“, ...", val 3, val_4
它有4個值,
并且該值"one value with 23'', 25\", 20“, end value"應作為 1 值讀入:value with 23'', 25\", 20“, end value
但是我嘗試過的所有選項要么最終跳過這些行或將它們讀入錯誤的列,要么只是給出錯誤并將資料讀入資料幀失敗
編輯:根據 BeRT2me 的請求,這里是來自 CSV 之一的行的更好示例,其中包含“實際”資料。(我無法提供任何“實際”值,因此以相同格式輸入假資料)
標題:
start_date,end_date,product_code,available,category_rank,brand,name,category,price
csv中的資料行:
2022-10-05,2022-10-10,3716372837,1.0,"",brand1,"Puzzle map of the world, 300 pieces, 23” x 15\", great for all ages",Games,39.99
uj5u.com熱心網友回復:
給定test.txt:
start_date, end_date, product_code, available, category_rank, brand,name,category,price
2022-10-05,2022-10-10,3716372837,1.0,"",brand1,"Puzzle, 300'' p, 23” x 15\", great",Games,39.99
正在做:
df = pd.read_csv('test.txt', escapechar='\\')
print(df)
輸出:
start_date end_date product_code available category_rank brand name category price
0 2022-10-05 2022-10-10 3716372837 1.0 NaN brand1 Puzzle, 300'' p, 23” x 15", great Games 39.99
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/520940.html
標籤:Python熊猫CSV
上一篇:創建類后,如何在不使用模塊的情況下將csv中的資訊添加到python物件
下一篇:決議CSV檔案時超時
