Kazım Mert Şahin
Kazım Mert Şahin

Reputation: 13

How to add one list's items to another list, one by one?

I have a csv file with some contents as shown below:

name,x,y
N1,30.2356,12.5263
N2,30.2452,12.5300

...and it goes on.

This is what I tried, I called them from .csv and seperately added to different lists.

import csv

nn = []
xkoor = []
ykoor = []
coord = []
with open('C:/Users/Mert/Desktop/py/transformation/1.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        nn.append(row[0].split(','))
        xkoor.append(row[1].split(','))
        ykoor.append(row[2].split(','))

j = 1
for i in range(len(xkoor)):
    for j in range(len(ykoor)):

I'm trying to make a list as:

coord = [30.2356,12.5263],[30.2452,12.5300],....

and I couldn't understand how to do it. Any ideas?

Upvotes: 0

Views: 169

Answers (6)

Jan
Jan

Reputation: 43199

If you are into oneliners:

data = """name,x,y
N1,30.2356,12.5263
N2,30.2452,12.5300"""

coords = [[x,y]
          for line in data.split("\n")[1:]
          for _,x,y in [line.split(",")]]
print(coords)

This yields

[['30.2356', '12.5263'], ['30.2452', '12.5300']]

Upvotes: 0

Halfow
Halfow

Reputation: 77

I'd go about it something like this:

import csv

# coordinates as strings 
with open('some.csv', 'r') as f:
    cord = [a for _, *a in csv.reader(f)]

# coordinates as floats
with open('some.csv', 'r') as f:
    cord = [[float(x), float(y)] for _, x, y in csv.reader(f)]

[print(xy) for xy in cord]

Upvotes: 0

C.Nivs
C.Nivs

Reputation: 13136

The csv-reader should split rows for you by commas on default:

import csv

with open('somefile.csv') as fh:
    reader = csv.reader(fh)
    for row in reader:
        print(row)

# outputs
['name', 'x', 'y']
['N1', '30.2356', '12.5263']
['N2', '30.2452', '12.5300 ']

With this in mind, if you are just looking to loop over coords, you can use unpacking to get your x and y, then build your list by appending tuples:

import csv

coords = []

with open('somefile.csv') as fh:
    reader = csv.reader(fh)
    next(reader) # skips the headers
    for row in reader:
        name, x, y = row
        coords.append((float(x), float(y)))

# then you can iterate over that list like so
for x, y in coords:
    # do something

Coords will then look like:

[(30.2356, 12.5263), (30.2452, 12.53)]

Upvotes: 2

jose_bacoy
jose_bacoy

Reputation: 12714

Why not pandas?!

  • read_csv will ready your file and convert as a dataframe
  • iterate on rows and access columns x and y
  • combine into a list of list

and it is easier to use

    import pandas as pd
    df = pd.read_csv('1.csv', header=0)
    [[r.x, r.y] for _, r in df.iterrows()]

Result:

[[30.2356, 12.5263], [30.2452, 12.53]]

Upvotes: 0

blhsing
blhsing

Reputation: 107134

You should not split the strings by commas yourself since csv.reader already does it for you. Simply iterate over the csv.reader generator and unpack the columns as desired:

reader = csv.reader(f)
next(reader)
coord = [[float(x), float(y)] for _, x, y in reader]

Upvotes: 1

Philippe Haussmann
Philippe Haussmann

Reputation: 538

Seems like you're over-complicating things.

If all you're trying to do is create an array of coordinates containing only the X and Y values, this is how you would accomplish that:

import csv
coord = []
with open('C:/Users/Mert/Desktop/py/transformation/1.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        rowlist = row.split(',')
        coord.append(rowlist[1:3])
print(coord)

All you need to do is extract a subset on a per-row basis, and append it to your coord array. No need to call row split each time, or to create separate arrays for your axis.

K.I.S.S!

(Also, a word of advice - keep PII out of your questions. No need to use your whole windows file path, just indicate that it's a CSV file. I didn't need to know your name to answer the question!)

Upvotes: 0

Related Questions