2017-02-23 67 views
1

我在.net文件中有一個來自客戶端的非常難看的數據導入。我已經設法將其轉換爲列表清單。列表的一個例子是gven:大雜燴列表中的大熊貓數據框

['* Table: Movement one\n', 
'* \n', 
'$TSYS:CODE;NAME;TYPE;PCU\n', 
'A;Car;PrT;1.000\n', 
'Air_Bus;Airport Bus;PuT;1.000\n', 
'B;Bus;PuT;1.000\n', 
'C;Company Bus;PrT;2.000\n', 
'CB;City Bus;PuT;1.000\n',', 
'FE;Ferry;PuT;1.000\n', 
'GV1;2-Axle Rigid Goods Vehicle;PrT;1.500\n', 
'GV2;3/4 Axle Rigid Goods Vehicle;PrT;2.000\n', 
'GV3;3/4 Axle Artic Goods Vehicle;PrT;3.000\n', 
'GV4;5+ Axle Artic Goods Vehicle;PrT;3.000\n', 
'IB;Intercity Bus;PuT;1.000\n', 
'IN;Industry Bus;PuT;1.000\n', 
'Loc;Local Bus;PuT;1.000\n', 
'LR;Light Rail;PuT;1.000\n', 
'R;Rail;PuT;1.000\n', 
'S;School Bus;PrT;2.000\n', 
'T;Taxi;PrT;1.100\n', 
'TR;Tram;PuT;1.000\n', 
'W;Walk;PrT;0.000\n', 
'WB;WaterBus;PuT;1.000\n', 
'WT;Water Taxi;PuT;1.000\n', 
'W_PuT;Walk_PuT;PuTWalk;1.000\n', 
'\n', 
'* \n'] 

我想加載到一個熊貓數據框。

頂部兩行和底部兩行可能會被丟棄。每個列表都包含一個字符串記錄,其中包含;分隔符。我知道read_csv的分隔符函數存在,但是這不起作用,因爲此時我沒有從文件讀取數據。列標題也很複雜。必須丟棄第一個$TSYS記錄,其餘的記錄用作列名稱。我可以使用strip刪除每條記錄中的\n

我試圖簡單地加載的數據幀:

results_df = pd.DataFrame(results[2:-2]) 
print(results_df.head()) 

           0 
0  $TSYS:CODE;NAME;TYPE;PCU\n 
1    A;Car;PrT;1.000\n 
3 Air_Bus;Airport Bus;PuT;1.000\n 
4    B;Bus;PuT;1.000\n 

因爲我有很多這樣的名單,我怎麼程式設計走3號線,刪除第一個字符串,並從剩餘的創建列標題?我如何正確分離;爲每個後續記錄?

回答

1

可以使用list comprehensionstripsplit值刪除\n

results_df = pd.DataFrame([x.strip().split(';') for x in results[3:-2]]) 
results_df.columns = results[2].strip().split(';') 

print(results_df) 

    $TSYS:CODE       NAME  TYPE PCU 
0   A       Car  PrT 1.000 
1  Air_Bus     Airport Bus  PuT 1.000 
2   B       Bus  PuT 1.000 
3   C     Company Bus  PrT 2.000 
4   CB      City Bus  PuT 1.000 
5   FE       Ferry  PuT 1.000 
6   GV1 2-Axle Rigid Goods Vehicle  PrT 1.500 
7   GV2 3/4 Axle Rigid Goods Vehicle  PrT 2.000 
8   GV3 3/4 Axle Artic Goods Vehicle  PrT 3.000 
9   GV4 5+ Axle Artic Goods Vehicle  PrT 3.000 
10   IB     Intercity Bus  PuT 1.000 
11   IN     Industry Bus  PuT 1.000 
12  Loc      Local Bus  PuT 1.000 
13   LR     Light Rail  PuT 1.000 
14   R       Rail  PuT 1.000 
15   S     School Bus  PrT 2.000 
16   T       Taxi  PrT 1.100 
17   TR       Tram  PuT 1.000 
18   W       Walk  PrT 0.000 
19   WB      WaterBus  PuT 1.000 
20   WT     Water Taxi  PuT 1.000 
21  W_PuT      Walk_PuT PuTWalk 1.000 
+0

感謝你。 8分鐘,直到我可以接受;) – LearningSlowly

+1

很高興能幫助你!祝你好運,謝謝。 – jezrael