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 do I add a column to a pandas dataframe which has the highest value in a range but applying it to every row?

I have the following code:

import pandas as pd
import numpy as np

df = pd.DataFrame([['red', 1], ['red', 13], ['red', 1], ['blue', 1], ['red', 112], ['blue', 10]])

df.columns = ["colour","rank"]

# df['highest_rank'] = ...

print(df)

"""
  colour  rank  highest_rank
0    red     1     122
1    red    13     122
2    red     1     122
3   blue     1     10
4    red   112     122
5   blue    10     10
"""

Hopefully, the example can show you what I’m trying to do as I’m struggling to describe what I’m wanting – The highest ranking of each colour.

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 :

groupby colour and broadcast the highest rank in each group using transform. Code below

df['highest_rank']=df.groupby('colour')['rank'].transform('max')




colour  rank  highest_rank
0    red     1           112
1    red    13           112
2    red     1           112
3   blue     1            10
4    red   112           112
5   blue    10            10
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