CSV file reading and vector line storage

Asked

Viewed 234 times

2

I need to read a csv file and store each one line of the file into different vectors. After that, convert these vectors to new csv files.

The problem is that my code generates two vectors with data from columns of csv.

What I’m trying to do is:

import os
import csv

os.chdir(r'C:\Users\')

coord1=[]

file = csv.reader(open(arquivo,'r'))
for row in file:
    coord1.append(row[0])

What could I do?

1 answer

-1

TL;DR

If I got it right, Voce can do using Dataframe pandas to read the file and then convert the values to type list python. I created an example to show this, as Voce did not exemplify csv, I simulated one with only 3 columns and 4 rows, I read the file to a DataFrame and in the end I create 3 'vectors', one with all lines, and the other two alternating one line for each one.

import pandas as pd
import io

s = ''' 
Nome,Sobrenome,Telefone
Foo,Bar,9-6666-6666
John,Doe,9-7777-7777
Lena,Luthor, 9-8888-8888
Peter,Gabriel, 9-9999-9999
'''

# Lendo o csv 
df = pd.read_csv(io.StringIO(s), usecols=['Nome', 'Sobrenome', 'Telefone'])

# Imprimindo o resultado
print('\n',df)

print('','Vetor com todas as linhas:', df.values.tolist(), sep='\n')
print('','Vetor com as linhas nas posicoes pares:',df.values.tolist()[::2], sep='\n') 
print('','Vetor com as linhas nas posicoes impares:',df.values.tolist()[1::2], sep='\n')

Exit:

     Nome Sobrenome      Telefone
0    Foo       Bar   9-6666-6666
1   John       Doe   9-7777-7777
2   Lena    Luthor   9-8888-8888
3  Peter   Gabriel   9-9999-9999

Vetor com todas as linhas:
[['Foo', 'Bar', '9-6666-6666'], ['John', 'Doe', '9-7777-7777'], ['Lena', 'Luthor', ' 9-8888-8888'], ['Peter', 'Gabriel', ' 9-9999-9999']]

Vetor com os elementos nas posicoes pares:
[['Foo', 'Bar', '9-6666-6666'], ['Lena', 'Luthor', ' 9-8888-8888']]

Vetor com os elementos nas posicoes impares:
[['John', 'Doe', '9-7777-7777'], ['Peter', 'Gabriel', ' 9-9999-9999']]


See working on repl.it.

  • Wow, for me to keep trying to help, could you explain why the downvote?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.