如何在python库中隔离数据帧中的最大值
我试图用python隔离并打印pandas数据帧中的最大值如何在python库中隔离数据帧中的最大值,python,pandas,Python,Pandas,我试图用python隔离并打印pandas数据帧中的最大值 # Data frame: df >> 0 A B C 0 0 0 0 0 A 0 -3 -3 5 B 0 -3 -6 2 C 0 5 0 -3 D 0 5 2 -3 E 0 0 10 5 F 0 -3 5 15 我已成功使用以下代码隔离该值: x = df.max(
# Data frame:
df
>> 0 A B C
0 0 0 0 0
A 0 -3 -3 5
B 0 -3 -6 2
C 0 5 0 -3
D 0 5 2 -3
E 0 0 10 5
F 0 -3 5 15
我已成功使用以下代码隔离该值:
x = df.max(axis=0)
maxValue = max(x)
maxValue
>> 15
但是如何访问此元素?是否有一种迭代数据帧元素的方法,以便
for elements in df:
if element == maxValue:
m = element
还是说那些话?我需要找到最大的元素,在本例中是15,并在本例中检索其位置,即(C,F)。然后我需要存储它,然后找到围绕第一个元素的下一个最大元素,以及它的位置
# desired output
[(C,F), (B,E), (A,D)]
我希望这是有意义的!如果您能就如何实施这一点提供任何建议,我将不胜感激!:) 我理解问题对最大值排序是必要的,所以如果nedd省略了第一列,则使用,然后对于最大值的位置,使用
max
对其进行排序,将其选择到系列
并最后转换到元组列表:
L = (list(df.iloc[:, 1:]
.agg(['idxmax','max'])
.sort_values('max', axis=1, ascending=False)
.loc['idxmax'].items()))
print (L)
[('C', 'F'), ('B', 'E'), ('A', 'C')]
对于所有列,删除iloc:
L = (list(df.agg(['idxmax','max'])
.sort_values('max', axis=1, ascending=False)
.loc['idxmax'].items()))
print (L)
[('C', 'F'), ('B', 'E'), ('A', 'C'), ('0', '0')]
您可以使用:
#replace 'df.iloc[:,1:]' with 'df' if first column isnt 0
out = [*df.iloc[:,1:][::-1].idxmax().items()]
#[('A', 'D'), ('B', 'E'), ('C', 'F')]
IIUC
sort\u值
+stack
df.stack().sort_values().groupby(level=1).tail(1).index.tolist()
Out[229]: [('A', '0'), ('D', 'A'), ('E', 'B'), ('F', 'C')]
这回答了你的问题吗?我尝试了此操作,但得到了一个类型错误:此数据类型不允许使用缩减操作“argmax”?@CharlieVagg您可以尝试
[*df.iloc[:,1:][:-1].astype(float).idxmax().items()
?我得到的输出是:[@CharlieVagg对我来说很好,可能是一些版本问题不确定try列表(df.iloc[:,1[::::-1].astype(float).idxmax().items())
但如果您使用示例数据进行测试,如果所有列都是数字,那么它确实可以工作。我使用的是python 2,而不是3,它现在已经工作了。非常感谢你!我得到一个键错误:“idxmax”。你知道为什么会这样吗?@CharlieVagg-是的,数据不是数字。尝试L=(列表(df.select\u数据类型(np.number).agg(['idxmax','max'])。排序\u值('max',axis=1,升序=False)。loc['idxmax'].items())打印(L)