Pandas数据框来自凌乱的列表列表

时间:2017-02-23 14:10:50

标签: python pandas

我在.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']

我希望将其加载到pandas数据帧中。

可以丢弃前两行和后两行。每个列表都包含一个字符串记录,其中包含;个分隔符。我知道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 个答案:

答案 0 :(得分:1)

您可以list comprehension使用\nstrip值删除split

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