Python 返回其中一个轴具有最大值的数据帧的所有条目?
我相信这是一个非常基本的问题,但我似乎找不到任何解决这个问题的方法 我有一个数据帧,比如下面的数据帧,我需要找到最大值“B”的条目。在下面的例子中,我希望条目2和条目3的B=25。任何返回条目索引或整个条目的解决方案都可以Python 返回其中一个轴具有最大值的数据帧的所有条目?,python,pandas,Python,Pandas,我相信这是一个非常基本的问题,但我似乎找不到任何解决这个问题的方法 我有一个数据帧,比如下面的数据帧,我需要找到最大值“B”的条目。在下面的例子中,我希望条目2和条目3的B=25。任何返回条目索引或整个条目的解决方案都可以 Name: 6417, dtype: float64 A B C 0 8.00 0 0 1 24.00 20 5 2 31.20 25 10 3 30.00
Name: 6417, dtype: float64
A B C
0 8.00 0 0
1 24.00 20 5
2 31.20 25 10
3 30.00 25 15
4 3.20 20 20
注意:我看到一些帖子谈到使用pd.idxmax(),但这只返回一个条目的索引,即使给定轴的最大值有多个条目
干杯我会这样做:
def函数(数据帧):
列表_max,max=[],0
对于dataframe.itertuples()中的行:
如果第B行>最大值:
最大值=第B行
列表_max.clear()
列表\u最大追加(行索引)
elif row.B=最大值:
列表\u最大追加(行索引)
返回列表\u max,max
正如@anky_91所说,使用获取所需的值
数据={
“A”:[8.00,24.00,31.20,30.00,3.20],
“B”:[0,20,25,25,20],
“C”:[0,5,10,15,20]
}
df=pd.DataFrame(数据)
max_b=df[df['b']==df['b'].max()
最大b.头()
产出:
abc
2 31.2 25 10
3 30.0 25 15
基本上,df['B']==df['B'].max()
0 False
1 False
2 True
3 True
4 False
Name: B, dtype: bool
df
使用它过滤掉行并只保留真正的行
#input data
d = {'A': [8,7,7,2,3], 'B': [0,20,25,25,20], 'C': [8,7,7,2,3]}
df = pd.DataFrame(data=d)
#sorting by values in column B
df = df.sort_values(by=['B'], ascending=False)
#finding the max value in column B
maxValue = df['B'].max()
#finding rows which have max value in column B
n = df.loc[df['B'] == maxValue]
#printing the result
print(n)
输出:
A B C
2 7 25 7
3 2 25 2
您可以使用布尔索引与max进行比较并返回:output=df[df['B'].eq(df['B'].max())]
第二步(按B列中的值排序)实际上不需要,对此表示抱歉