简体   繁体   English

如何将多个无序行与大熊猫合并为单个行[CSV文件]

[英]How to combine multiple unordered rows into a single row with pandas [CSV file]

I have data in the following format in csv file 我在csv文件中具有以下格式的数据

1) Pedestrian; 1)行人; - ; -; - ; -; - ; -; - ; -; 5.74; 5.74; 0.018771; 0.018771; 2080.04; 2080.04; 522.40; 522.40; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 2080.04; 2080.04; 522.40; 522.40; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 41.7083; 41.7083; 2080.04; 2080.04; 522.40; 522.40; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 83.4167 83.4167

; ; 2080.04; 2080.04; 522.40; 522.40; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 125.1250; 125.1250; 2080.04; 2080.04; 522.40; 522.40; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 0.0000; 166.8333; 166.8333;

2) Pedestrian; 2)行人; - ; -; - ; -; - ; -; - ; -; 5.74; 5.74; 0.018771;2104.25; 0.018771; 2104.25; 528.51; 528.51; 0.0671; 0.0671; -0.3212; -0.3212; -0.1091; -0.1091; 178595.0833; 178595.0833; 2104.30; 2104.30;

528.53; 528.53; 0.0566; 0.0566; -0.3056; -0.3056; -0.1113; -0.1113; 178636.7917; 178636.7917; 2104.34; 2104.34; 528.56; 528.56; 0.0466; 0.0466; -0.2926; -0.2926; -0.1125; -0.1125; 178678.5000 ; 178678.5000; 2104.39; 2104.39; 528.58; 528.58; 0.0375; 0.0375; -0.2613; -0.2613; -0.1128; -0.1128; 178720.2083; 178720.2083; 2104.44; 2104.44; 528.61; 528.61; 0.0299; 0.0299; -0.2221; -0.2221; -0.1116; -0.1116;

78761.9167; 78761.9167; 2104.48; 2104.48; 528.63; 528.63; 0.0235; 0.0235; -0.0841; -0.0841; -0.1063; -0.1063; 178803.625; 178803.625;

This csv file don't have header and also, each row don't have same order. 此csv文件没有标题,并且每一行也没有相同的顺序。 For example, some row ends with semicolon(;) but some rows end with numbers and some rows started with semicolon. 例如,某些行以分号(;)结尾,但某些行以数字结尾,而某些行以分号开头。 I want to change the format like this: 我想这样改变格式:

1; Pedestrian; - ; - ; - ; - ; 5.74; 0.018771; ----------------------------------------------

2; Pedestrian; - ; - ; - ; - ; 5.74; 0.018771;-----------------------------------------------

Is there any elegant solution? 有什么优雅的解决方案吗?

This might help. 这可能会有所帮助。 You can use the csv module to read your file. 您可以使用csv module读取文件。

Ex: 例如:

import csv
s = "PATH_TO.csv"

res = []
with open(s, 'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=';')
    for line in reader:
        if line:
            if ")" in line[0]:
                print "; ".join(line[:7]), "-"*46

Output: 输出:

1) Pedestrian;  - ;  - ;  - ;  - ;  5.74;  0.018771; ----------------------------------------------
2) Pedestrian;  - ;  - ;  - ;  - ;  5.74;  0.018771; ----------------------------------------------

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM