熊猫:如何显示列的最大差异?

时间:2018-08-17 11:00:21

标签: pandas

我正在使用(result['column1'] - result['column2']).abs().idxmax()来查找两列之间的最大差异。但这只会将“索引”返回给我,而不会实际显示该值。

例如:

Breeders    number of cats  number of dogs
a                  5               25
b                  15              15
c                  25              10

如果我使用(result['number of cats'] - result['number of dogs']).abs().idxmax() 它将返回'a'

如果我想要类似'a' with a difference of 20的输出怎么办?

2 个答案:

答案 0 :(得分:1)

首先创建Series,然后使用format打印idxmaxmax值:

s = (result['number of cats'] - result['number of dogs']).abs()
print (s)
a    20
b     0
c    15
dtype: int64

print ('{} with a difference of {}'.format(s.idxmax(), s.max()))
#thanks @jpp for python 3.6+ solution
#print(f'{s.idxmax()} with a difference of {s.max()}')
a with a difference of 20

原始解决方案:

a = (result['number of cats'] - result['number of dogs']).abs().agg(['idxmax','max'])
print (a)
idxmax     a
max       20
dtype: object

print ('{} with a difference of {}'.format(a['idxmax'], a['max']))
a with a difference of 20

答案 1 :(得分:1)

另一个选择:

max_ix = (result['number of cats'] - result['number of dogs']).abs().idxmax()
max_br = result.loc[max_ix, "Breeders"]
max_diff = abs(result.loc[max_ix, 'number of cats'] - result.loc[max_ix, 'number of dogs'])
print  max_br + ' with a difference of ' + str(max_diff)