我有一個與 .csv 非常相似的 .txt 檔案,但不完全相同。正如您所看到的,前 4 列可以用空格分隔,但最后一個字串將被拆分為不同數量的列。我需要最后一個字串只是一列。
09 4 10/11/2021 22:21:17 The PLC reported that sorter SS02 has E-stopped.
08 4 10/11/2021 22:21:17 The PLC reported that sorter SS02 has stopped.
08 4 10/11/2021 22:21:18 The PLC reported that sorter SS01 has stopped.
20 5 10/11/2021 22:21:18 The PLC reported that purge mode was disabled for sorter SS02.
20 5 10/11/2021 22:21:18 The PLC reported that purge mode was disabled for sorter SS01.
23 5 10/11/2021 22:21:19 AUX Sortation has been enabled for sorter SS02.
23 5 10/11/2021 22:21:20 AUX Sortation has been enabled for sorter SS01.
我怎樣才能讀到這個,所以我只有 5 個一致的列?稍后我可能會將日期和時間合并為一列。
uj5u.com熱心網友回復:
您可以預先決議每一行,然后創建 DataFrame,例如:
import pandas as pd
with open('input.txt') as f_input:
data = [line.strip().split(' ', 4) for line in f_input]
df = pd.DataFrame(data, columns=['c1', 'c2', 'date', 'time', 'desc'])
print(df)
給你:
c1 c2 date time desc
0 09 4 10/11/2021 22:21:17 The PLC reported that sorter SS02 has E-stopped.
1 08 4 10/11/2021 22:21:17 The PLC reported that sorter SS02 has stopped.
2 08 4 10/11/2021 22:21:18 The PLC reported that sorter SS01 has stopped.
3 20 5 10/11/2021 22:21:18 The PLC reported that purge mode was disabled for sorter SS02.
4 20 5 10/11/2021 22:21:18 The PLC reported that purge mode was disabled for sorter SS01.
5 23 5 10/11/2021 22:21:19 AUX Sortation has been enabled for sorter SS02.
6 23 5 10/11/2021 22:21:20 AUX Sortation has been enabled for sorter SS01.
可以通過組合date和time列并將它們轉換為日期時間來添加日期時間列:
df['datetime'] = pd.to_datetime(df['date'] ' ' df['time'])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/329901.html
