Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Fill Column Cells with Column Name by Position

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This would be fairly simple with iloc:

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

   col1  col2  col3
0     1     3  col3
1     2     4  col3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading