Reputation: 395
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
Upvotes: 0
Views: 403
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
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