如何从特定列中提取数据并将其分离?

2024-05-08 17:10:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我对CSV有疑问,我有如下CSV数据:

Runway | Data1  | Data2  | Data3      |
   13   | 425   | 23    | Go Straight |
        | 222   | 24    | Go Straight |
        | 424   | 25    | Go Left     |
---------------------------------------
   16   | 555   | 13    | Go Right    |
        | 858   | 14    | Go Right    |
        | 665   | 15    | Go Straight |

我怎样才能把它变成像这样的独立跑道:

 Runway | Data1 | Data2 | Data3       | S | Runway | Data1 | Data2 | Data3  |
   13   | 425   | 23    | Go Straight | P |   16   | 555   | 13    | Go Right    |
        | 222   | 24    | Go Straight | A |        | 858   | 14    | Go Right    |
        | 424   | 25    | Go Left     | C |        | 
        |       |       |             | E | 

这可能吗?多谢各位


Tags: csv数据rightgoleftstraightrunwaydata1
1条回答
网友
1楼 · 发布于 2024-05-08 17:10:51

抱歉花了这么长时间,这是我的代码,我试着简单一点

import csv

with open("file_name.csv", "r") as file:
    csv_reader = csv.reader(file, delimiter = ',')
    csv_reader = list(csv_reader)
    # Get table header and pop it
    header = csv_reader.pop(0)

    # Recursive function to extract and large row
    def getLargeRow(rows, csvRows = []):
        if (len(rows) != 0):
            largeRow = [rows.pop(0)]
            while (rows != [] and rows[0][0] == ''):
                largeRow.append(rows.pop(0))
            csvRows.append(largeRow)
            return getLargeRow(rows, csvRows)
        else:
            return csvRows

    # Now we have all rows as an list of lists
    rows = getLargeRow(csv_reader)

    # Assuming that all large rows got the same height (same number of regular rows)
    largeRowsHeight = len(rows[0])
    # Amount of large rows
    largeRowsAmount = len(rows)

    print(rows)

    # The new text of a new csv file
    newCsvFileText = ''
    for i in range(largeRowsAmount):
        newCsvFileText += ','.join(header)
        if i < largeRowsAmount - 1:
            newCsvFileText += ',,'
    newCsvFileText += '\n'
    for i in range(largeRowsHeight):
        for j, row in enumerate(rows):
            newCsvFileText += ','.join(row[i])
            if j < len(rows) - 1:
                newCsvFileText += ',,'
        newCsvFileText += '\n'

    # Save into a new file
    with open("new_file.csv", "w") as newfile:
        newfile.write(newCsvFileText)

相关问题 更多 >