如何获取panda数据帧df的行数?


当前回答

您也可以这样做:

假设df是您的数据帧。然后df.shape为您提供数据帧的形状,即(行,列)

因此,分配以下命令以获得所需的

 row = df.shape[0], col = df.shape[1]

其他回答

假设df是您的数据帧,那么:

count_row = df.shape[0]  # Gives number of rows
count_col = df.shape[1]  # Gives number of columns

或者更简洁地说,

r, c = df.shape

TL;DR使用长度(df)

len()返回列表对象的项数(长度)(也适用于字典、字符串、元组或范围对象)。因此,要获取DataFrame的行计数,只需使用len(df)。有关len函数的更多信息,请参见官方页面。


或者,您可以分别使用df.index和df.columns访问所有行和所有列len(df.index)将给出行数,len(df.columns)将给出列数。

或者,您可以使用df.shape,它一起返回行数和列数(作为元组),在这里您可以使用索引访问每个项。如果要访问行数,请仅使用df.shape[0]。对于列数,请只使用:df.shape[1]。

…建立在Jan Philip Gehrcke的答案之上。

len(df)或len(df.index)比df.shape[0]更快的原因是:

看看代码。df.shape是一个@属性,它运行两次调用len的DataFrame方法。

df.shape??
Type:        property
String form: <property object at 0x1127b33c0>
Source:
# df.shape.fget
@property
def shape(self):
    """
    Return a tuple representing the dimensionality of the DataFrame.
    """
    return len(self.index), len(self.columns)

在len(df)的罩下

df.__len__??
Signature: df.__len__()
Source:
    def __len__(self):
        """Returns length of info axis, but here we use the index """
        return len(self.index)
File:      ~/miniconda2/lib/python2.7/site-packages/pandas/core/frame.py
Type:      instancemethod

len(df.index)将比len(df)稍快,因为它少了一个函数调用,但这总是比df.shape[0]快

如果要在链接操作的中间获取行数,可以使用:

df.pipe(len)

例子:

row_count = (
      pd.DataFrame(np.random.rand(3,4))
      .reset_index()
      .pipe(len)
)

如果您不想在len()函数中放一个长语句,这可能很有用。

您可以改用__len__(),但__len__)看起来有点奇怪。

除了前面的答案之外,您还可以使用df.axes获取具有行和列索引的元组,然后使用len()函数:

total_rows = len(df.axes[0])
total_cols = len(df.axes[1])