LLTeng
LLTeng

Reputation: 395

Auto create pandas column based on a define number of columns

how can I define a function to dynamically create a pandas data frame and the number of columns based on a user input number?

For example: no_levels = 3

enter image description here

Upvotes: 0

Views: 403

Answers (2)

Anurag Dabas
Anurag Dabas

Reputation: 24324

Try something like:

def create(cols):
    col=['Level'+str(x) for x in range(1,cols+1)]
    return pd.DataFrame(columns=col)


create(4)

OR

as @anky suggested:

def create(cols):
    return pd.DataFrame(columns=range(1,cols+1)).add_prefix("Level")

create(4)

Output:

Level1  Level2  Level3  Level4

Upvotes: 2

Sagun Devkota
Sagun Devkota

Reputation: 505

You can try.

df=pd.DataFrame({})
no_lvl=int(input("number of levels"))
for lvl in range(no_lvl):
    df["level_"+str(lvl+1)]=None

Upvotes: 2

Related Questions