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

Pandas: copying values of a certain row based on a different column

What I’m trying to achieve is that when a row in col2 has a 1, it will copy that 1 onto all the other values in col2 as long as the rows in col1 have the same name. As an example, if the dataframe looks like this

col1  col2
xx      1
xx      0
xx      0
xx      0
yy      0
yy      0
yy      0
zz      0
zz      0
zz      1

The output would be

col1  col2
xx      1
xx      1
xx      1
xx      1
yy      0
yy      0
yy      0
zz      1
zz      1
zz      1

I’m really new to python and don’t have a single clue how to even approach this issue. Any help would be greatly appreciated.

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 :

Use groupby.transform('max'):

df['col2'] = df.groupby('col1')['col2'].transform('max')

Output:

  col1  col2
0   xx     1
1   xx     1
2   xx     1
3   xx     1
4   yy     0
5   yy     0
6   yy     0
7   zz     1
8   zz     1
9   zz     1
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