简体   繁体   中英

How to add multiple new columns in pandas data frame without assigning their names manually?

I have a list of strings which I want them to be the names of the new columns I want to add to the data frame.

enter code here
  for i in len(range(col_name_lis)):
        name = col_name_lis[i]
        merged_df.insert(col_len, name , "")

but this gives me this error: 'list' object cannot be interpreted as an integer

You need to switch the order of len(range(...)) to range(len(...)):

col_name_list = ["column 1", "column 2", "column 3"]
df = pd.DataFrame()
for i in range(len(col_name_list)):
    name = col_name_list[i]
    df[name] = ""

Better yet, use a shorthand for list iteration:

col_name_list = ["column 1", "column 2", "column 3"]
for name in col_name_list:
    df[name] = ""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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