I have a question about how to load and distinguish Python csv files.

Asked 1 years ago, Updated 1 years ago, 416 views

I have to load the csv file and distinguish the data, but I can't think of a way, so I'm asking you a question. ㅜ분명히 I'm sure there's a way, but I don't know how to search it.

There is a csv file in the following format:

As you can see from the format, the first column represents the X coordinate and the second column represents the Y coordinate. Also, starting with # is an explanation of what the information below means.

I would like to divide one CSV file into several data frames using the file above. For example, I want to separate COLINE into one data frame and LNDARE into another data frame.

After loading CSV into data frames, is there a way to distinguish it as above? I would like the result to be in the following format.

COLINE = Data frame with row 2,3,4,5 (column names are X,Y)

LNDARE = Data frame with row 7, 8, 9, 10 (column names are X,Y)

The process of preprocessing data with Python is still difficult... I need your help. <

pandas dataframe csv python

2023-02-11 19:50

1 Answers

import csv

import pandas as pd

f = open("data.csv", "r")
reader = csv.reader(f)
datas = {}
flag = "DEFAULT"

for line in reader:
    if line[0].find("COLINE") > 0:
        flag = "COLINE"
    elif line[0].find("LNDARE") > 0:
        flag = "LNDARE"
    else:
        if flag not in datas.keys():
            datas[flag] = {"x": [], "y": []}
        datas[flag]["x"].append(line[0])
        datas[flag]["y"].append(line[1])

coline = pd.DataFrame(datas["COLINE"])
lndare = pd.DataFrame(datas["LNDARE"])

print(coline)
print(lndare)
# output
     x     y
0   50   100
1  100   100
2  100    50
3   50    50
      x      y
0   -50   -100
1  -100   -100
2  -100    -50
3   -50    -50

Are you sure you're talking about this?


2023-02-11 23:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.