简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM