我有一個非常簡單的檔案:
[Name]
Streamline 1
[Data]
X [ m ], Y [ m ], Z [ m ], Velocity [ m s^-1 ]
2.66747564e-01, 0.00000000e 00, 2.03140453e-01, (0.00000000e 00, 8.17744827e 00, 0.00000000e 00)
2.66958952e-01, 0.00000000e 00, 2.07407191e-01, (0.00000000e 00, 6.77392197e 00, 0.00000000e 00)
2.63460875e-01, 0.00000000e 00, 2.06593186e-01, (0.00000000e 00, 7.04168701e 00, 0.00000000e 00)
2.65424699e-01, 0.00000000e 00, 2.00831652e-01, (0.00000000e 00, 8.93691921e 00, 0.00000000e 00)
2.70607203e-01, 0.00000000e 00, 2.02286631e-01, (0.00000000e 00, 8.45830917e 00, 0.00000000e 00)
2.68299729e-01, 0.00000000e 00, 1.97365344e-01, (0.00000000e 00, 1.00771456e 01, 0.00000000e 00)
...
我需要將速度作為向量加載到單行中。
我的基本代碼:
df = pd.read_csv("C:/Users/Marek/Downloads/0deg-5ms.csv", skiprows=5)
但是這種嘗試導致 1st 2 cols 成為索引,其余的分成 4 列。index_col=False可以解決index的問題,但是會導致index超出范圍。我需要一個分隔符,它隱式地告訴熊貓忽略括號中的任何內容。我認為python在讀取csv檔案時會忽略帶括號的分隔符可能會起作用,但是是的,我到處都有空格。我發現了一些使用擴展函式來加載檔案并按行處理它們的解決方案,例如CSV 檔案包含括號中偶爾有逗號的列會崩潰 pandas.read_csv和Load CSV with data by parentheses into a pandas dataframe。然而,我相信這是一個非常簡單的場景,因為所有行都相似,可以通過單行添加來解決delimiter='some_regex'. 然而,我無法弄清楚這個正則運算式應該是什么樣子。它應該尋找分隔符,而不是(.*,.*).
我嘗試了以下操作,但這會導致一列:
df = pd.read_csv("C:/Users/Marek/Downloads/0deg-5ms.csv", skiprows=5, delimiter=',^(\(.*,.*\))')
編輯:得到了這樣的 - ,|(?:(\(.*,.*\))),但這會在每個逗號后添加一個空列。
uj5u.com熱心網友回復:
您可以手動決議檔案:
data = []
with open('data.csv') as fp:
[next(fp) for i in range(5)] # skiprows=5
headers = [c.strip() for c in next(fp).split(',')]
for line in fp:
data.append([i.strip() for i in re.split(r',(?![^\(]*[\)])', line)])
df = pd.DataFrame(data, columns=headers).apply(pd.eval)
輸出:
>>> df
X [ m ] Y [ m ] Z [ m ] Velocity [ m s^-1 ]
0 0.266748 0.0 0.203140 [0.0, 8.17744827, 0.0]
1 0.266959 0.0 0.207407 [0.0, 6.77392197, 0.0]
2 0.263461 0.0 0.206593 [0.0, 7.04168701, 0.0]
3 0.265425 0.0 0.200832 [0.0, 8.93691921, 0.0]
4 0.270607 0.0 0.202287 [0.0, 8.45830917, 0.0]
5 0.268300 0.0 0.197365 [0.0, 10.0771456, 0.0]
>>> df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 6 entries, 0 to 5
Data columns (total 4 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 X [ m ] 6 non-null float64
1 Y [ m ] 6 non-null float64
2 Z [ m ] 6 non-null float64
3 Velocity [ m s^-1 ] 6 non-null object
dtypes: float64(3), object(1)
memory usage: 320.0 bytes
>>> type(df.iloc[0, 3]) # [0.0, 8.17744827, 0.0]
list
>>> type(df.iloc[0, 3][1]) # 8.17744827
float
uj5u.com熱心網友回復:
經過多次嘗試,我找到了如何在此基礎上創建一個非常簡單的單線的答案。如果有人感興趣,這里是:
df = pd.read_csv("C:/Users/Marek/Downloads/0deg-5ms.csv", skiprows=5, delimiter=',(?![^\(]*[\)])', engine="python")
分隔符檢查括號外所有內容中的逗號。像魅力一樣簡單:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/321818.html
