I am trying to place multiple columns (Score1, Score2, Score3 etc) before columns whose name begins with a certain text e.g.: Certainty.
I can insert columns at fixed locations using:
df.insert(17, "Score1", " ")
Adding a column then changes the column sequence, so then I would have to look and see where the next column is located. I can add a list of blank columns to the end of a CSV.
So essentially, my understanding is that I have to get pandas to read the column header. If the header text starts with "Certainty", then place a column called Score1 before it.
I tried using:
df.insert(df.filter(regex='Certainty').columns, "Score", " ")
However, as can be guessed it doesn't work.
From what I understand is that pandas is not efficient at iterative methods? Am I misinformed here?
Writing this also leads me to think that it needs a counter for Score1, 2, 3.
Any suggestions would be appreciated!
Thanks in advance.
Updates------Based on feedback provided
Using the method by @SergeBallesta works.
cur=0
for i, col in enumerate(df.columns):
if col.startswith('Certainty'):
df.insert(i+cur, f'Score{cur + 1}', '')
cur += 1
Using the method by @JacoSolari I needed to make a modification to allow it to find all columns starting with "Certainty". And also needed to add Score1, Score2, Score3 automatically.
Version 1: This only adds Score1 in the correct place and then nothing else
counter=0
certcol = df.columns[df.columns.str.contains('Certainty')]
col_idx = df.columns.get_loc(certcol[0])
col_names = [f'Score{counter + 1}']
[df.insert(col_idx, col_name, ' ')
for col_name in col_names[::-1]]
Version 2: This adds Score1 in the correct place and then adds the rest after the first "Certainty" column. So it does not proceed to find the next one. Perhaps it needs a for
loop somewhere?
cur=0
certcol = df.columns[df.columns.str.contains('Certainty')]
for col in enumerate(certcol):
col_idx = df.columns.get_loc(certcol[0])
df.insert(cur+col_idx, f'Score{cur + 1}', '')
cur += 1
I have posted this, in case anyone stumbles across the same need.