Home > other >  How to Fill Column Cells with Column Name by Position
How to Fill Column Cells with Column Name by Position

Time:07-08

I am an amateur Python user (aka beginner), and want to solve the following problem: Use a column name based on its position and not its name, and then fill the column with the name of that column. Here is the original data:

data = {'col1': [1, 2], 'col2': [3, 4],'col3': [0,0]}
df = pd.DataFrame(data)
df

    col1  col2  col3
0     1     3     0
1     2     4     0

Here is the desired result. Again, I don't necessarily know the name of the column, just its position, so the code should not actually have reference to "col3", but to its location, in this case 2 (2nd from the 0 position).


   col1  col2  col3
0     1     3  col3
1     2     4  col3

CodePudding user response:

This would be fairly simple with iloc:

df.iloc[:, 2] = df.columns[2]

   col1  col2  col3
0     1     3  col3
1     2     4  col3
  • Related