如何获取panda数据帧df的行数?
当前回答
使用len(df)或len(df.index)时,可能会遇到以下错误:
----> 4 df['id'] = np.arange(len(df.index)
TypeError: 'int' object is not callable
解决方案:
lengh = df.shape[0]
其他回答
…建立在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]快
对于dataframe df,在浏览数据时使用的打印逗号格式的行计数:
def nrow(df):
print("{:,}".format(df.shape[0]))
例子:
nrow(my_df)
12,456,789
这两种方法都可以做到(df是DataFrame的名称):
方法1:使用len函数:
len(df)将给出名为df的DataFrame中的行数。
方法2:使用计数函数:
df[col].count()将计算给定列col中的行数。
df.count()将给出所有列的行数。
我从R背景来到Pandas,我发现Pandas在选择行或列时更加复杂。
我不得不与它搏斗一段时间,然后我找到了一些应对方法:
获取列数:
len(df.columns)
## Here:
# df is your data.frame
# df.columns returns a string. It contains column's titles of the df.
# Then, "len()" gets the length of it.
获取行数:
len(df.index) # It's similar.
假设df是您的数据帧,那么:
count_row = df.shape[0] # Gives number of rows
count_col = df.shape[1] # Gives number of columns
或者更简洁地说,
r, c = df.shape
推荐文章
- 如何在Flask-SQLAlchemy中按id删除记录
- 在Python中插入列表的第一个位置
- Python Pandas只合并某些列
- 如何在一行中连接两个集而不使用“|”
- 从字符串中移除前缀
- 代码结束时发出警报
- 如何在Python中按字母顺序排序字符串中的字母
- 在matplotlib中将y轴标签添加到次要y轴
- 如何消除数独方块的凹凸缺陷?
- 为什么出现这个UnboundLocalError(闭包)?
- 使用Python请求的异步请求
- 如何检查一个对象是否是python中的生成器对象?
- 如何从Python包内读取(静态)文件?
- 如何计算一个逻辑sigmoid函数在Python?
- python: SyntaxError: EOL扫描字符串文字