問題
我有一個以管道分隔的資料集,其中一些值也有管道。這些元素在任一側被包圍,\\表示它們之間的管道不應用作分隔符。原始資料如下所示:
Col1|Col2|Col3
1|some text|more text
2|some text|more text
3|\\text with a | in it\\|more text
4|\\a|b|c\\|more text
我想將這些讀入熊貓資料框,使其看起來像:
| Col1 | Col2 | Col3 |
|---|---|---|
| 1 | 一些文字 | 更多文字 |
| 2 | 一些文字 | 更多文字 |
| 3 | 帶有 | 的文本 在里面 | 更多文字 |
| 4 | a|b|c | 更多文字 |
嘗試 1
如果我只是使用
pd.read_csv(path, sep='|')
我得到錯誤
---------------------------------------------------------------------------
ParserError Traceback (most recent call last)
...
pandas/_libs/parsers.pyx in pandas._libs.parsers.raise_parser_error()
ParserError: Error tokenizing data. C error: Expected 3 fields in line 3, saw 4
因為引擎將第 3 行解釋為有 4 列。
嘗試 2
我認為這可以使用quotechar引數解決(參考檔案)
pd.read_csv(path, sep='|', quotechar='\\')
但這會將值保留為 NaN 而不是正確決議
| Col1 | Col2 | Col3 |
|---|---|---|
| 1 | 一些文字 | 更多文字 |
| 2 | 一些文字 | 更多文字 |
| 3 | 鈉 | 更多文字 |
| 4 | 鈉 | 更多文字 |
嘗試 3
我嘗試使用該comment引數(盡管我認為這不是它的預期用途并且得到了與嘗試 2 相同的結果。
pd.read_csv(path, sep='|', comment='\\')
uj5u.com熱心網友回復:
不幸的是,“quotechar”引數僅限于一個字符。在你的情況下,你有兩個。
您可以做的是預處理檔案內容以替換\\為另一個字符,例如規范雙引號"
import io
path = 'test.csv'
with open(path) as f:
df = pd.read_csv(io.StringIO(f.read().replace(r'\\', '"')), sep='|')
print(df)
輸出:
Col1 Col2 Col3
1 some text more text NaN
2 some text more text NaN
3 text with a | in it more text NaN
4 a|b|c more text NaN
注意。|除了標題之外,每行末尾都有一個額外的,這是預期的嗎?
uj5u.com熱心網友回復:
quotechar='\\'對您不起作用的原因是因為quotechar假設任何超過一個字符的引數都是正則運算式。
我會嘗試用一個反斜杠替換那個雙反斜杠。嘗試這樣的事情也許:
from io import StringIO
import pandas as pd
doubleslash = r"\\"
with open("test.csv", newline="") as f:
file = StringIO(f.read().replace(doubleslash, "\\"))
frame = pd.read_csv(file, delimiter="|", quotechar="\\")
print(frame)
請注意,我們必須將雙反斜杠定義為原始字串,并且我們正在轉義引號字符和替換字符欄位中的反斜杠。
您可以在這里看到類似的問題:https ://stackoverflow.com/a/60902745/18375093
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/461480.html
上一篇:管道通過但未創建csv檔案
