I require to create multiple new dataframe columns in one step. My approach was to ask the user “How many columns are required?” and based on the user input, that much new columns should be created at one go.
Following is my requirement in the form of code:
df1.insert(len(df1.columns),'Syndata_1997', np.nan) df1.insert(len(df1.columns),'Syndata_1998', np.nan) df1.insert(len(df1.columns),'Syndata_1999', np.nan) df1.insert(len(df1.columns),'Syndata_2000', np.nan)
so to elaborate, instead of using insert function to create a column one by one, I want 4 columns with naming and values as NaN to be created when the user gives input as 4 something like this:
prompt=int(input('Enter the columns to be created:'))
Then, based on value of prompt, new columns should be created.
Please let me know if this can be done or any other method to create columns automatically.
Advertisement
Answer
You can use the assign command –
num_cols = 10 df.assign(**{f'Syndata_{idx}': np.nan for idx in range(num_cols)})