简体   繁体   English

如何向 pandas dataframe 添加一列,该列在一个范围内具有最高值但将其应用于每一行?

[英]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. groupby 颜色并使用变换广播每组中的最高排名。 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取连续熊猫中具有最高值的列的名称 - How do I get the name of the column with the highest value in a row pandas 将函数应用于Pandas中数据框列的每一行 - Applying a function to every row in a dataframe column in Pandas 在熊猫中,如何删除所有子行,但在multiIndex数据帧的特定列中保留值最高的子行? - In Pandas how to remove all subrows but keep one which has the highest value in a specific column in a multiIndex dataframe? 如何删除数据帧中值高于特定阈值的每一行? - How do I remove every row in a dataframe which has a value above a certain threshold? pandas:获取列和行名称,其中行对每一行具有最高值 - pandas: get column and row name where row has the highest value for every row 如何为 Pandas 数据框列中的每个唯一值添加重复的月份行? - How do I add repeated month rows for every unique value in a pandas dataframe column? 如何在pandas数据帧的第二行中添加列标题? - How do i add column header, in the second row in a pandas dataframe? Python:如何编写 function 以确定 dataframe 中的哪个变量与指定列的绝对相关性最高? - Python: How do I write a function to determine which variable in a dataframe has the highest absolute correlation with a specified column? 如何将字符串添加到pandas dataframe列系列中的每个偶数行? - How to add a string to every even row in a pandas dataframe column series? 如何使用pandas删除数据框中具有空列的行 - how to remove a row which has empty column in a dataframe using pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM