我在.net文件中从客户端导入了非常丑陋的数据。我设法将其转换为列表列表。清单的一个例子是:

['* 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


由于我有很多这样的列表,如何以编程方式选择第三行,删除第一个字符串,并从其余的行创建列标题?如何正确区分每个后续记录的;

最佳答案

您可以使用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

07-28 02:45
查看更多