1

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
Sam
  • 209
  • 2
  • 11

1 Answers1

1

This would be fairly simple with iloc:

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

   col1  col2  col3
0     1     3  col3
1     2     4  col3
Shubham Sharma
  • 68,127
  • 6
  • 24
  • 53