最近我想做一些排序,计算,并找到数据帧中的最大值。 例如:
data = {'Name':['Penny','Ben','Benny','Mark'],
'Eng':[5,1,4,3],
'Math':[1,5,3,2],
'Physics':[2,5,3,1],
'Sports':[4,5,2,3],
'Total':[12,16,12,9]}
df1=pd.DataFrame(data, columns=['Name','Eng','Math','Physics','Sports','Total'])
df1
我想得到不同主题的范围,然后找到一个函数
numpy.ptp
可以找到沿轴的值范围(最大值-最小值), 所以我这样做 将numpy作为np导入
cols_of_interest = ['Eng','Math','Sports','Physics']
np.ptp(df1[cols_of_interest].values, axis=1)
结果
array([4, 4, 2, 2])
当我得到结果时,来自数据帧的信息丢失了。例如,我想找到范围最大的学生 应该是(佩妮:4,本:4) 但是,当数据大小较大时,如何将这些数据合并回数据帧并找到最大值
另外,对于cols_of_interest = ['Eng','Math','Sports','Physics']
,当元素很大(比如100个主题)时,有没有优雅的方法来应用np.ptp
非常感谢
只需分配
np.ptp
的输出:df1['max_range'] = np.ptp(df1[cols_of_interest].values, axis=1)
最后,您可以通过以下方法找到最大值:
max_val = df1['max_range'].max()
或df1['max_range'].idxmax()
如果需要最大值的索引您可以使用
df1.columns
访问数据帧的列。这将返回列的列表;然后简单地从该列表中删除您不想要的名称,并将其传递到np.ptp
相关问题 更多 >
编程相关推荐