如何获取panda数据帧df的行数?
当前回答
假设数据集是“data”,将数据集命名为“data_fr”,data_fr中的行数为“nu_rows”
#import the data frame. Extention could be different as csv,xlsx or etc.
data_fr = pd.read_csv('data.csv')
#print the number of rows
nu_rows = data_fr.shape[0]
print(nu_rows)
其他回答
…建立在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是DataFrame的名称):
方法1:使用len函数:
len(df)将给出名为df的DataFrame中的行数。
方法2:使用计数函数:
df[col].count()将计算给定列col中的行数。
df.count()将给出所有列的行数。
使用len(df)或len(df.index)时,可能会遇到以下错误:
----> 4 df['id'] = np.arange(len(df.index)
TypeError: 'int' object is not callable
解决方案:
lengh = df.shape[0]
假设df是您的数据帧,那么:
count_row = df.shape[0] # Gives number of rows
count_col = df.shape[1] # Gives number of columns
或者更简洁地说,
r, c = df.shape
我不确定这是否可行(数据可以省略),但这可能可行:
*dataframe name*.tails(1)
然后使用这个,您可以通过运行代码片段并查看提供给您的行号来找到行数。
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 无法切换Python与pyenv
- Python if not == vs if !=
- 确定每列中NA值的个数
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- 如何合并字典的字典?
- 如何创建类属性?
- 如何结合多个条件子集数据帧使用“或”?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- 解析日期字符串并更改格式