Python Find max in dataframe 列以循环查找所有值

标签 python python-3.x pandas numpy dataframe

所以我有一个使用 pandas 的大型数据框。

当我这样做时max(df['A'])它报告的最大值为 9999什么时候应该是396450通过观察。

import numpy as numpy
import pandas as pd

f = open("20170901.as-rel2.txt", 'r')
#read file into array, ignore first 6 lines
lines = loadtxt("20170901.as-rel2.txt", dtype='str', comments="#", delimiter="|", unpack=False)
#ignore col 4
lines=lines[:, :3]
#convert to dataframe
df = pd.DataFrame(lines, columns=['A', 'B', 'C'])

找到最大值后,我必须计算每个 node(col 'A')并说出重复了多少次。

以下是该文件的示例:

df=
                 A       B   C
    0            2   45714   0
    1            2   52685  -1
    2            3     293   0
    3            3   23248  -1
    4            3  133296   0
    5            3  265301  -1
    6            5   28599  -1
    7            5   52352   0
    8            5  262879  -1
    9            5  265048  -1
    10           5  265316  -1
    11          10   46392   0
    .....
    384338  396238   62605  -1
    384339  396371    3785  -1
    384340  396434   35039  -1
    384341  396450    2495  -1
    384342  396450    5078  -1

    Expect:
    [1, 0
    2, 2
    3, 4
    4, 0
    5, 5
    10, 1
    ....]

我打算运行一个 for i <= maxvalue 的循环(最大值超过行数)。 并使用计数器。最有效的方法是什么?

最佳答案

np.bincount

pd.Series(np.bincount(df.A))

0     0
1     0
2     2
3     4
4     0
5     5
6     0
7     0
8     0
9     0
10    1
dtype: int64

关于Python Find max in dataframe 列以循环查找所有值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53231776/

相关文章:

python - 创建第二个 Toplevel 小部件时线程化 Tkinter 脚本崩溃

python - Tkinter radiobutton IntVar 属性错误

python - 在 Flask 中将表单 POST 对象转换为适合 mongodb 的表示形式

python - 如何在Python 3中重用父类(super class)方法的变量?

python - 如果列表中包含相应属性的另一个数据帧的值,如何添加列检查?

python - 尝试遵循 Python Elasticsearch 示例用法时出现“连接被拒绝”错误

python-3.x - 具有周期性边界条件和输出对距离的 KDTree

python-3.x - 如何等到声音文件以 Python 3.6 中的 vlc 结尾

Python:关于 pandas 列的多个条件问题

python - 如何从 pandas Dataframe 创建单个字典?