pandas python如何计算数据帧中的记录或行数

Ice*_*lin 21 count dataframe pandas

对熊猫来说显然是新手.我怎样才能简单地计算数据帧中的记录数.

我会想到一些简单的事情会这样做,我甚至无法在搜索中找到答案......可能是因为它太简单了.

cnt = df.count
print cnt
Run Code Online (Sandbox Code Playgroud)

上面的代码实际上只是打印整个df

use*_*737 21

要获取数据框中的行数,请使用:

df.shape[0]
Run Code Online (Sandbox Code Playgroud)

(并df.shape[1]获得列数).

作为替代方案,您可以使用

len(df)
Run Code Online (Sandbox Code Playgroud)

要么

len(df.index)
Run Code Online (Sandbox Code Playgroud)

(和len(df.columns)列)

shape比起来更通用,更方便len(),特别是对于交互式工作(最后只需要添加),但len速度要快一些(参见本答复).

要避免:count()因为它返回了请求轴上的非NA/null观察数

len(df.index) 是比较快的

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(24).reshape(8, 3),columns=['A', 'B', 'C'])
df['A'][5]=np.nan
df
# Out:
#     A   B   C
# 0   0   1   2
# 1   3   4   5
# 2   6   7   8
# 3   9  10  11
# 4  12  13  14
# 5 NaN  16  17
# 6  18  19  20
# 7  21  22  23

%timeit df.shape[0]
# 100000 loops, best of 3: 4.22 µs per loop

%timeit len(df)
# 100000 loops, best of 3: 2.26 µs per loop

%timeit len(df.index)
# 1000000 loops, best of 3: 1.46 µs per loop
Run Code Online (Sandbox Code Playgroud)

df.__len__ 只是打电话给 len(df.index)

import inspect 
print(inspect.getsource(pd.DataFrame.__len__))
# Out:
#     def __len__(self):
#         """Returns length of info axis, but here we use the index """
#         return len(self.index)
Run Code Online (Sandbox Code Playgroud)

为什么你不应该使用 count()

df.count()
# Out:
# A    7
# B    8
# C    8
Run Code Online (Sandbox Code Playgroud)


tsh*_*uck 20

关注你的问题......计算一个字段?我决定提出一个问题,但我希望它有所帮助......

说我有以下DataFrame

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])
Run Code Online (Sandbox Code Playgroud)

你可以算一个列

df.A.count()
#or
df['A'].count()
Run Code Online (Sandbox Code Playgroud)

两者评价为5.

很酷的事情(或许多wrt中的一个pandas)是,如果你有NA价值观,那么数量会考虑到这一点.

所以,如果我这样做

df['A'][1::2] = np.NAN
df.count()
Run Code Online (Sandbox Code Playgroud)

结果将是

 A    3
 B    5
Run Code Online (Sandbox Code Playgroud)


Sur*_*rya 8

简单地说,row_num = df.shape [0] #给出行数,这里是示例:

import pandas as pd
import numpy as np

In [322]: df = pd.DataFrame(np.random.randn(5,2), columns=["col_1", "col_2"])

In [323]: df
Out[323]: 
      col_1     col_2
0 -0.894268  1.309041
1 -0.120667 -0.241292
2  0.076168 -1.071099
3  1.387217  0.622877
4 -0.488452  0.317882

In [324]: df.shape
Out[324]: (5, 2)

In [325]: df.shape[0]   ## Gives no. of rows/records
Out[325]: 5

In [326]: df.shape[1]   ## Gives no. of columns
Out[326]: 2
Run Code Online (Sandbox Code Playgroud)