Home > Blockchain >  How do i use loops to add columns to a data frame in python
How do i use loops to add columns to a data frame in python

Time:09-12

clean_data.insert(loc=0,column = 'Grade Point x Credit Units', value = 'N.A')
clean_data.insert(loc=0,column = 'Credit Unit', value = 'N.A')
clean_data.insert(loc=0,column = 'Grade Point', value = 'N.A')
clean_data.insert(loc=0,column = 'Grade', value = 'N.A')

CodePudding user response:

You don't need a loop to add columns:

clean_data = pd.DataFrame({'TheColumn0': [1, 2, 3, 4]})
cols = ['Grade', 'Grade Point', 'Credit Unit', 'Grade Point x Credit Units']
clean_data = clean_data.assign(**{c: 'N.A' for c in cols}).reindex(columns=cols   list(clean_data.columns))
print(clean_data)

Prints:

  Grade Grade Point Credit Unit Grade Point x Credit Units  TheColumn0
0   N.A         N.A         N.A                        N.A           1
1   N.A         N.A         N.A                        N.A           2
2   N.A         N.A         N.A                        N.A           3
3   N.A         N.A         N.A                        N.A           4

CodePudding user response:

Create a list and loop over the names

column_names = ['Grade Point x Credit Units','Credit Unit','Grade Point','Grade']

for column_name in column_names:
  clean_data.insert(loc = 0, column = column_name, value = 'N.A')
  • Related