简体   繁体   English

如何根据输入数字添加多个新的 dataframe 列?

[英]How to add multiple new dataframe columns based on an input number?

I require to create multiple new dataframe columns in one step.我需要一步创建多个新的 dataframe 列。 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.并且根据用户输入,应该在一个 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:所以要详细说明,而不是使用插入 function 来一一创建一列,我希望在用户输入 4 时创建 4 个命名和值为 NaN 的列,如下所示:

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.请让我知道这是否可以完成或任何其他自动创建列的方法。

You can use the assign command -您可以使用分配命令 -

num_cols = 10

df.assign(**{f'Syndata_{idx}': np.nan for idx in range(num_cols)})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM