Taie
Taie

Reputation: 1179

Add new columns iteratively to a dataframe with a unique column name

I have a dataframe going into a for loop. In each loop, a new column is added to the dataframe. The number of columns is unknown. How can I make column naming in this situation automatic, such that each time the program adds a new column, that column gets a unique name, as shown below:

x  xx  xxx xxxx xxxxx
1  12  14
2  24  26
3  64  66

I tried cumcount() with add_prefix() but it didn't work. Any suggestions?

Upvotes: 1

Views: 758

Answers (1)

Sultan Singh Atwal
Sultan Singh Atwal

Reputation: 820

You can try adding a counter variable to the loop and name the new column based on the counter variable. You can increment the counter variable by some constant value each time the loop executes so that each new column added has a unique name in each iteration of the loop. Something like this (assuming 'df' to be the name of the data frame):

i = 0
for j in #range of loop:
    df[i] = #new column
    i += 1

This will give numerical names to the new columns added (like 0, 1, 2, 3.... and so on) and you will also be able to identify which column was added in which iteration.

Upvotes: 2

Related Questions