如何计算数量大熊猫每行出现次数最多?

时间:2016-02-19 04:37:16

标签: python pandas

df = pd.DataFrame([[1,2,3,1,5],
                   [2,3,4,4,6],
                   [7,2,2,2,5],
                   [21,3,4,3,6]], index=[1,2,3,4], columns=list('ABCDE'))

df的结果值

    A   B   C   D   E
1   1   2   3   1   5
2   2   3   4   4   6
3   7   2   2   2   5
4   21  3   4   3   6

我怎么知道哪一个数字在每一行中出现次数最多?

例如:

row 1: 1    appears two times
row 2: 4    appears two times
row 3: 2    appears three times

依旧......

2 个答案:

答案 0 :(得分:3)

您可以使用applyvalue_counts获取值{和出现次数concat以加入它们:

value = df.apply(lambda x: x.value_counts().index[0], axis=1)
count = df.apply(lambda x: x.value_counts().iloc[0], axis=1)

out = pd.concat([value, count], axis=1).reset_index()

out.columns = ['row_num', 'val', 'appearing']
out['row_num'] = 'row ' + out['row_num'].astype(str) + ':'
out['appearing'] = 'appears ' + out['appearing'].astype(str) + ' times'

In [64]: out
Out[64]:
  row_num  val        appearing
0  row 1:    1  appears 2 times
1  row 2:    4  appears 2 times
2  row 3:    2  appears 3 times
3  row 4:    3  appears 2 times

答案 1 :(得分:1)

for idx, i in df.iterrows():
    l = list(i)
    list_of_counts = [l.count(x) for x in l]
    m = max(list_of_counts)
    print ("row " + str(idx) + ":" + str(l[list_of_counts.index(m)]) +" appears " + str(m) +" times")

第1行:1次出现2次

第2行:4出现2次

第3行:2次出现3次

第4行:3次出现2次