Reputation: 11
I have a csv file. test.csv
1,1,1,1
I want to load this as variables.
My code:
import pandas as pd
ch_file=pd.read_csv("test.csv")
ch1_value=ch_file.columns[0]
ch2_value=ch_file.columns[1]
ch3_value=ch_file.columns[2]
ch4_value=ch_file.columns[3]
print(ch1_value, ch2_value, ch3_value,
ch4_value)
Output is 1,1.1,1,1.1
Why does it not print 1,1,1,1
?
Where is the .1
coming from?
Upvotes: 1
Views: 37
Reputation: 120391
You have 2 problems here:
When you use read_csv
the first line is interpreted as the column headers. You have to pass header=None
if you have not.
ch_file.columns[2]
return the column name and not the value(s). Instead, use .iloc
.
ch_file = pd.read_csv('test.csv', sep=',', header=None)
ch1_value=ch_file.iloc[0, 0]
ch2_value=ch_file.iloc[0, 1]
ch3_value=ch_file.iloc[0, 2]
ch4_value=ch_file.iloc[0, 3]
print(ch1_value, ch2_value, ch3_value, ch4_value)
Output:
1 1 1 1
Upvotes: 1
Reputation: 260300
What do you want to extract? Just the numbers?
pandas.read_csv
rewrites the column names to be unique, so it will add .1
, .2
, etc. for this. In theory you could pass the mangle_dupe_cols=False
option, but it is not supported yet.
An alternative it to pass header=None
and to get the values of the first row:
pd.read_csv('test.csv', header=None).iloc[0]
In your case:
ch1_value, ch2_value, ch3_value, ch4_value = pd.read_csv('test.csv', header=None).iloc[0]
But, honestly, do you really need pandas
for this? You could do it directly in pure python:
with open('test.csv') as f:
ch1_value, ch2_value, ch3_value, ch4_value = map(int, f.readline().split(','))
Upvotes: 1