如何获取panda数据帧df的行数?
当前回答
这两种方法都可以做到(df是DataFrame的名称):
方法1:使用len函数:
len(df)将给出名为df的DataFrame中的行数。
方法2:使用计数函数:
df[col].count()将计算给定列col中的行数。
df.count()将给出所有列的行数。
其他回答
对于数据帧df,可以使用以下任一项:
长度(df.索引)df.形状[0]df[df.columns[0]].count()(==第一列中非NaN值的数量)
再现绘图的代码:
import numpy as np
import pandas as pd
import perfplot
perfplot.save(
"out.png",
setup=lambda n: pd.DataFrame(np.arange(n * 3).reshape(n, 3)),
n_range=[2**k for k in range(25)],
kernels=[
lambda df: len(df.index),
lambda df: df.shape[0],
lambda df: df[df.columns[0]].count(),
],
labels=["len(df.index)", "df.shape[0]", "df[df.columns[0]].count()"],
xlabel="Number of rows",
)
假设df是您的数据帧,那么:
count_row = df.shape[0] # Gives number of rows
count_col = df.shape[1] # Gives number of columns
或者更简洁地说,
r, c = df.shape
…建立在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是您的数据帧。然后df.shape为您提供数据帧的形状,即(行,列)
因此,分配以下命令以获得所需的
row = df.shape[0], col = df.shape[1]
使用len(df)或len(df.index)时,可能会遇到以下错误:
----> 4 df['id'] = np.arange(len(df.index)
TypeError: 'int' object is not callable
解决方案:
lengh = df.shape[0]
推荐文章
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本
- 我在哪里调用Keras的BatchNormalization函数?
- 打印测试执行时间并使用py.test锁定缓慢的测试
- 插入一行到熊猫数据框架
- 要列出Pandas DataFrame列
- 在Django模型中存储电话号码的最佳方法是什么?
- 从导入的模块中模拟函数