yem*_*emu 786 python dataframe pandas
我正在尝试用Pandas获取dataframe df的行数,这是我的代码.
total_rows = df.count
print total_rows +1
Run Code Online (Sandbox Code Playgroud)
total_rows = df['First_columnn_label'].count
print total_rows +1
Run Code Online (Sandbox Code Playgroud)
两个代码片段都给我这个错误:
TypeError:+:'instancemethod'和'int'的不支持的操作数类型
我究竟做错了什么?
roo*_*oot 1064
您可以使用.shape酒店或只是len(DataFrame.index).但是,有显着的性能差异(len(DataFrame.index)最快):
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: df = pd.DataFrame(np.arange(12).reshape(4,3))
In [4]: df
Out[4]:
0 1 2
0 0 1 2
1 3 4 5
2 6 7 8
3 9 10 11
In [5]: df.shape
Out[5]: (4, 3)
In [6]: timeit df.shape
2.77 µs ± 644 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [7]: timeit df[0].count()
348 µs ± 1.31 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In [8]: len(df.index)
Out[8]: 4
In [9]: timeit len(df.index)
990 ns ± 4.97 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Run Code Online (Sandbox Code Playgroud)

编辑:作为@丹·艾伦在评论中指出的len(df.index)和df[0].count()不能互换的count不包括NaNS,
Nas*_*hah 248
假设df您的数据帧是:
count_row = df.shape[0] # gives number of row count
count_col = df.shape[1] # gives number of col count
Run Code Online (Sandbox Code Playgroud)
Jan*_*cke 127
使用len(df).这适用于pandas 0.11或甚至更早.
__len__()目前(0.12)记录在案Returns length of index.时间信息,设置方式与root的答案相同:
In [7]: timeit len(df.index)
1000000 loops, best of 3: 248 ns per loop
In [8]: timeit len(df)
1000000 loops, best of 3: 573 ns per loop
Run Code Online (Sandbox Code Playgroud)
由于一个额外的函数调用它比len(df.index)直接调用慢一点,但这在大多数用例中不起任何作用.
cs9*_*s95 52
如何获取大熊猫DataFrame的行数?
下表总结了您希望在DataFrame(或Series,为了完整起见)中进行计数的不同情况,以及推荐的方法。
脚注
DataFrame.countSeries由于非空计数随列而异,因此返回每一列的计数。DataFrameGroupBy.size返回Series,因为同一组中的所有列共享相同的行数。DataFrameGroupBy.count返回一个DataFrame,因为非空计数在同一组的各列之间可能有所不同。要获取特定列的逐组非空计数,请使用df.groupby(...)['x'].count()“ x”为要计数的列。
下面,我显示上表中描述的每种方法的示例。首先,设置-
df = pd.DataFrame({
'A': list('aabbc'), 'B': ['x', 'x', np.nan, 'x', np.nan]})
s = df['B'].copy()
df
A B
0 a x
1 a x
2 b NaN
3 b x
4 c NaN
s
0 x
1 x
2 NaN
3 x
4 NaN
Name: B, dtype: object
Run Code Online (Sandbox Code Playgroud)
len(df),df.shape[0]或len(df.index)len(df)
# 5
df.shape[0]
# 5
len(df.index)
# 5
Run Code Online (Sandbox Code Playgroud)
比较固定时间操作的性能似乎很愚蠢,尤其是当差异处于“严重不担心”级别时。但这似乎是带有其他答案的趋势,因此为了完整性,我也进行了同样的操作。
在上述3种方法中,len(df.index)(如其他答案所述)最快。
注意
- 上面的所有方法都是固定时间操作,因为它们是简单的属性查找。
df.shape(类似于ndarray.shape)是一个返回的元组的属性(# Rows, # Cols)。例如,此处df.shape返回(8, 2)示例。
df.shape[1],len(df.columns)df.shape[1]
# 2
len(df.columns)
# 2
Run Code Online (Sandbox Code Playgroud)
类似于len(df.index),len(df.columns)是这两种方法中比较快的一种(但键入的字符更多)。
len(s),s.size,len(s.index)len(s)
# 5
s.size
# 5
len(s.index)
# 5
Run Code Online (Sandbox Code Playgroud)
s.size而len(s.index)即将在速度方面是相同的。但我建议len(df)。
注意
size是一个属性,它返回元素数(=任何系列的行数)。DataFrames还定义了一个size属性,该属性返回与相同的结果df.shape[0] * df.shape[1]。
DataFrame.count和Series.count此处描述的方法仅计算非空值(表示忽略NaN)。
调用DataFrame.count将返回每列的非NaN计数:
df.count()
A 5
B 3
dtype: int64
Run Code Online (Sandbox Code Playgroud)
对于系列,请使用Series.count类似的效果:
s.count()
# 3
Run Code Online (Sandbox Code Playgroud)
GroupBy.size对于DataFrames,用于DataFrameGroupBy.size计算每个组的行数。
df.groupby('A').size()
A
a 2
b 2
c 1
dtype: int64
Run Code Online (Sandbox Code Playgroud)
同样,对于Series,您将使用SeriesGroupBy.size。
s.groupby(df.A).size()
A
a 2
b 2
c 1
Name: B, dtype: int64
Run Code Online (Sandbox Code Playgroud)
在两种情况下,Series都将返回a。这也很有意义,DataFrames因为所有组都共享相同的行数。
GroupBy.count与上述类似,但使用GroupBy.count而不是GroupBy.size。请注意,size始终返回a Series,而在特定列上count返回Seriesif,否则返回a DataFrame。
以下方法返回相同的内容:
df.groupby('A')['B'].size()
df.groupby('A').size()
A
a 2
b 2
c 1
Name: B, dtype: int64
Run Code Online (Sandbox Code Playgroud)
同时,count我们有
df.groupby('A').count()
B
A
a 2
b 1
c 0
Run Code Online (Sandbox Code Playgroud)
...在整个GroupBy对象v / s上调用
df.groupby('A')['B'].count()
A
a 2
b 1
c 0
Name: B, dtype: int64
Run Code Online (Sandbox Code Playgroud)
在特定列上调用。
Mem*_*min 24
len()是你的朋友,行数的简短回答是len(df).
另外,您也可以访问所有行df.index的所有列
df.columns,并且可以使用len(anyList)用于获取列表的数量,因此你可以使用
len(df.index)用于获取的行数,并len(df.columns)为列数.
或者,您可以使用df.shape它返回行数和列数,如果您想访问仅使用的行df.shape[0]数,并且列数仅使用:df.shape[1].
小智 18
除了上面的答案,use可以df.axes用来获取带有行索引和列索引的元组,然后使用len()函数:
total_rows=len(df.axes[0])
total_cols=len(df.axes[1])
Run Code Online (Sandbox Code Playgroud)
小智 15
对于数据框df:
当你仍在编写代码时:
len(df)df.shape[0]代码完成后最快:
len(df.index)在正常数据大小下,每个选项将在一秒内完成。因此,“最快”选项实际上是让您工作速度最快的选项,或者len(df)如果df.shape[0]您已经有一个子集df并且只想.shape[0]在交互式会话中短暂添加,则可以是这样。
在最终优化的代码中,最快的运行时间是len(df.index).
df[df.columns[0]].count()在上面的讨论中被省略,因为没有评论者指出它有用的情况。它的速度呈指数级缓慢,而且打字时间长。它提供第一列中非 NaN 值的数量。
重现情节的代码:
pip install pandas perfplot
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: len(df),
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",
)
Run Code Online (Sandbox Code Playgroud)
小智 7
你也可以这样做:
假设df是您的数据框。然后df.shape给你你的数据框的形状,即(row,col)
因此,分配以下命令以获取所需的
row = df.shape[0], col = df.shape[1]
Run Code Online (Sandbox Code Playgroud)
我从R背景来到熊猫,我发现在选择行或列时,大熊猫更复杂.我不得不与它搏斗一段时间,然后我找到了一些方法来处理:
得到列数:
len(df.columns)
## Here:
#df is your data.frame
#df.columns return a string, it contains column's titles of the df.
#Then, "len()" gets the length of it.
Run Code Online (Sandbox Code Playgroud)
获取行数:
len(df.index) #It's similar.
Run Code Online (Sandbox Code Playgroud)
......以Jan-Philip Gehrcke的答案为基础.
之所以len(df)或者len(df.index)比之快df.shape[0].看看代码.df.shape是一个@property运行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)
Run Code Online (Sandbox Code Playgroud)
在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
Run Code Online (Sandbox Code Playgroud)
len(df.index)会比稍微快一点的len(df)函数调用快一点,但总是快于df.shape[0]
如果您想在链式操作的中间获取行数,您可以使用:
df.pipe(len)
Run Code Online (Sandbox Code Playgroud)
例子:
row_count = (
pd.DataFrame(np.random.rand(3,4))
.reset_index()
.pipe(len)
)
Run Code Online (Sandbox Code Playgroud)
如果您不想在len()函数中放入长语句,这会很有用。
你可以__len__()改用,但__len__()看起来有点奇怪。
小智 6
这两者都可以做到(df是 DataFrame 的名称):
方法一:使用len函数:
len(df)将给出名为 的 DataFrame 中的行数df。
方法2:使用count函数:
df[col].count()将计算给定列中的行数col。
df.count()将给出所有列的行数。
| 归档时间: |
|
| 查看次数: |
1542125 次 |
| 最近记录: |