Joey
Joey

Reputation: 934

How to assign Dataframe column header names to column variable with iteration

I am trying to iterate through dataframe header names and assign each name to the respective column values such that printing the name of each header will print the column data assigned to that header name. Current code:

import pandas as pd

filepath = "...data"

df = pd.DataFrame.from_csv(filepath, header=0, index_col=None)

for i in list(df):
    print i
    i = str(i)
    i = df[i]

print(cal_z)

result:

C:\...TFS_plot.py"

wavelength (nm)
Mix1_p
Ccal_p
Mix1_zero
Cal_zero
Mix_deriv
Cal_deriv
Unnamed: 7
Mix1_raw
Cal_rawzero
Mix1_rawderiv

Traceback (most recent call last):
  File "C:\....TFS_plot.py", line 14, in <module>
    print(cal_z)
NameError: name 'Mix1_p' is not defined

Is there something wrong with the way I am assigning the iterator to the variable df[i]?

example data:

cat dog
3   1
2   2
1   4

print dog

result:

(1,2,4)

Upvotes: 1

Views: 4647

Answers (2)

Rayhane Mama
Rayhane Mama

Reputation: 2424

If your question is how to create variables with the same names of your DataFrame columns, and you want those variables to contain the values of their respective columns then this should help

import pandas as pd
df = pd.DataFrame ({'cat':[3,2,1],'dog':[1,2,4]})

for i in list(df):
    exec(i + " = df[i].values")
print(dog)
print(cat)

your variables will have their columns values as lists.

print(dog)
# returns [1 2 4]
print(cat)
# returns [3 2 1]

all you're doing is get the columns name ( i ) and pass the corresponding columns to it (df[i].values) using exec for that. Happy coding.

Upvotes: 4

Zw Zwieb Ieb
Zw Zwieb Ieb

Reputation: 26

Hi there is a way to do this. But as far as i now it would be better to just use a dictionary to store the variables.

use list(df) or df.columns.tolist() to get a list of your df's header then use the exec() function while iterrating over this List and store the according values

df = pd.DataFrame({"dog":[1,2,3,],"cat":[2,4,6]})
print(df)

output:

   cat  dog
0    2    1
1    4    2
2    6    3

list()-function

print(list(df))
['cat', 'dog']

exec()-Function

for name in list(df):
    exec("{}={}".format(name,list(df[name])))

afterwards you can call your list via the column name

Upvotes: 0

Related Questions