Ujjwal Mahajan
Ujjwal Mahajan

Reputation: 63

Make a dataframe column with names of variables in the for loop

I have an issue with my code. Below is the code snippet:

abc = [1, 2, 3, 4]
def = [5, 6, 7, 8]

for i in [abc, def]:
   df[str(i)] = i   #This is giving an issue

I want to make abc and def (list) a column in my dataframe with column name as abc and def (Same as in for loop.

Is it possible. Can anybody help please

Upvotes: 1

Views: 2457

Answers (2)

SeaBean
SeaBean

Reputation: 23217

You can leverage on the locals() function that acts like a dict to hold the local variables:

abc = [1, 2, 3, 4]
def1 = [5, 6, 7, 8]     # rename 'def' to 'def1' since 'def' is a Python keyword

df = pd.DataFrame()

for i in ['abc', 'def1']:
   df[i] = locals()[i]   

Here, locals()['abc'] will resolve to the variable name abc which holds [1, 2, 3, 4]. Thus, effectively it is the same as running the following code for the first iteration of the for loop:

df['abc] = [1, 2, 3, 4] 

Result:

print(df)

   abc  def1
0    1     5
1    2     6
2    3     7
3    4     8

Upvotes: 1

Corralien
Corralien

Reputation: 120409

You can't (easily) do that with your variable declaration. Maybe you can try:

cols = {'abc': [1, 2, 3, 4], 
        'def': [5, 6, 7, 8]}

out = pd.concat([df, pd.DataFrame(cols)], axis="columns")
>>> out
  xyz  abc  def
0   A    1    5
1   B    2    6
2   C    3    7
3   D    4    8

Upvotes: 1

Related Questions