How to read a csv file by pandas without erasing the first number?

Asked

Viewed 70 times

-1

Hello, I have a.csv file and I want to read with the pandas library in Python. When I run the command it takes the first 0 from the sequence of numbers. Can someone help me with this? I want him to keep the zeros in front of the same.csv file.

import pandas as pd
lista=pd.read_csv('~/caminho/meu_arquivo.csv')


#Esse é meu arquivo csv
"""
teste
01234567899
12345678909
23456789012
09876543211
"""
#Minha saída
"""
Out[98]: 
     teste
0   1234567899
1  12345678909
2  23456789012
3   9876543211

https://replit.com/@Dennisrochaa/test-1#main.py

1 answer

4


Archives CSV does not come with definition of the data types of your columns. So the Pandas module when reading a CSV should infer the most appropriate type of data.

In your case the test column has been evaluated as a numerical column. In numerical data types the left zeros are automatically deleted. Specify explicitly through the parameter dtype of the method pandas.read_csv() that the column is a string.

The parameter dtype can be filled with a dictionary and where the keys are the column names and the values the respective data types:

import pandas as pd

lista = pd.read_csv('./meu_arquivo.csv', dtype={"teste": str})
print(lista)
         teste
0  01234567899
1  12345678909
2  23456789012
3  09876543211

Test the code on Rep.it

Also dtype can be filled with a single data type where it will be applied in all columns:

import pandas as pd

lista = pd.read_csv('./meu_arquivo.csv', dtype=str)
print(lista)

Browser other questions tagged

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