your programing

Pandas DataFrame의 행 수를 어떻게 얻습니까?

lovepro 2020. 9. 29. 08:16
반응형

Pandas DataFrame의 행 수를 어떻게 얻습니까?


Pandas로 데이터 프레임 df의 행 수를 얻으려고하는데 여기에 내 코드가 있습니다.

방법 1 :

total_rows = df.count
print total_rows +1

방법 2 :

total_rows = df['First_columnn_label'].count
print total_rows +1

두 코드 조각 모두 다음과 같은 오류가 발생합니다.

TypeError : +에 대해 지원되지 않는 피연산자 유형 : 'instancemethod'및 'int'

내가 도대체 ​​뭘 잘못하고있는 겁니까?


.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)

여기에 이미지 설명 입력

편집 :로 @Dan 알렌은 코멘트에 언급 len(df.index)df[0].count()같은 교환 할 수 없습니다 count제외 NaN,의


df데이터 프레임이 다음과 같다고 가정 합니다.

count_row = df.shape[0]  # gives number of row count
count_col = df.shape[1]  # gives number of col count

또는 더 간결하게

r, c = df.shape

사용 len(df). 이것은 pandas 0.11 또는 그 이전 버전에서 작동합니다.

__len__()현재 (0.12) 문서화되어 Returns length of index있습니다. 타이밍 정보, 루트의 대답과 같은 방식으로 설정하십시오.

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

하나의 추가 함수 호출로 인해 len(df.index)직접 호출하는 것보다 약간 느리지 만 대부분의 사용 사례에서 어떤 역할도하지 않습니다.


Pandas DataFrame의 행 수를 어떻게 얻습니까?

이 표는 권장 방법과 함께 DataFrame (또는 완전성을 위해 Series)에서 무언가를 계산하려는 다양한 상황을 요약합니다.

여기에 이미지 설명 입력

각주

  1. DataFrame.countSeriesNull이 아닌 개수는 열에 따라 다르므로 각 열의 개수를로 반환합니다 .
  2. DataFrameGroupBy.sizeSeries동일한 그룹의 모든 열이 동일한 행 수를 공유하므로를 반환합니다 .
  3. DataFrameGroupBy.countDataFramenull이 아닌 개수는 동일한 그룹의 열간에 다를 수 있으므로를 반환합니다 . 특정 열에 대한 그룹 단위 Null이 아닌 수를 얻으려면 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

DataFrame의 행 개수 : len(df), df.shape[0], 또는len(df.index)

len(df)
# 5

df.shape[0]
# 5

len(df.index)
# 5

특히 차이가 "심각하게 걱정하지 마십시오"수준에있을 때 일정한 시간 작업의 성능을 비교하는 것은 어리석은 것처럼 보입니다. 하지만 이것은 다른 답변이있는 추세 인 것 같아서 완전성을 위해 똑같이하고 있습니다.

위의 세 가지 방법 중 len(df.index)(다른 답변에서 언급했듯이) 가장 빠릅니다.

노트

  • 위의 모든 메서드는 단순한 속성 조회이므로 일정 시간 작업입니다.
  • df.shape (similar to ndarray.shape) is an attribute that returns a tuple of (# Rows, # Cols). For example, df.shape returns (8, 2) for the example here.

Column Count of a DataFrame: df.shape[1], len(df.columns)

df.shape[1]
# 2

len(df.columns)
# 2

Analogous to len(df.index), len(df.columns) is the faster of the two methods (but takes more characters to type).

Row Count of a Series: len(s), s.size, len(s.index)

len(s)
# 5

s.size
# 5

len(s.index)
# 5

s.size and len(s.index) are about the same in terms of speed. But I recommend len(df).

Note
size is an attribute, and it returns the number of elements (=count of rows for any Series). DataFrames also define a size attribute which returns the same result as df.shape[0] * df.shape[1].

Non-Null Row Count: DataFrame.count and Series.count

The methods described here only count non-null values (meaning NaNs are ignored).

Calling DataFrame.count will return non-NaN counts for each column:

df.count()

A    5
B    3
dtype: int64

For Series, use Series.count to similar effect:

s.count()
# 3

Group-wise Row Count: GroupBy.size

For DataFrames, use DataFrameGroupBy.size to count the number of rows per group.

df.groupby('A').size()

A
a    2
b    2
c    1
dtype: int64

Similarly, for Series, you'll use SeriesGroupBy.size.

s.groupby(df.A).size()

A
a    2
b    2
c    1
Name: B, dtype: int64

In both cases, a Series is returned. This makes sense for DataFrames as well since all groups share the same row-count.

Group-wise Non-Null Row Count: GroupBy.count

Similar to above, but use GroupBy.count, not GroupBy.size. Note that size always returns a Series, while count returns a Series if called on a specific column, or else a DataFrame.

The following methods return the same thing:

df.groupby('A')['B'].size()
df.groupby('A').size()

A
a    2
b    2
c    1
Name: B, dtype: int64

Meanwhile, for count, we have

df.groupby('A').count()

   B
A   
a  2
b  1
c  0

...called on the entire GroupBy object, v/s,

df.groupby('A')['B'].count()

A
a    2
b    1
c    0
Name: B, dtype: int64

Called on a specific column.


len() is your friend, short answer for row counts is len(df).

Alternatively, you can access all rows by df.index and all columns by df.columns, and as you can use the len(anyList) for getting the count of list, hence you can use len(df.index) for getting the number of rows, and len(df.columns) for the column count.

Alternatively, you can use df.shape which returns the number of rows and columns together, if you want to access the number of rows only use df.shape[0] and for the number of columns only use: df.shape[1].


Apart from above answers use can use df.axes to get the tuple with row and column indexes and then use len() function:

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

I come to pandas from R background, and I see that pandas is more complicated when it comes to selecting row or column. I had to wrestle with it for a while, then I found some ways to deal with:

getting the number of columns:

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.

getting the number of rows:

len(df.index) #It's similar.

...building on Jan-Philip Gehrcke's answer.

The reason why len(df) or len(df.index) is faster than df.shape[0]. Look at the code. df.shape is a @property that runs a DataFrame method calling len twice.

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)

And beneath the hood of 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) will be slightly faster than len(df) since it has one less function call, but this is always faster than df.shape[0]


In case you want to get the row count in the middle of a chained operation, you can use:

df.pipe(len)

Example:

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

This can be useful if you don't want to put a long statement inside a len() function.

대신 __len __ ()을 사용할 수 있지만 __len __ ()은 약간 이상해 보입니다.


데이터 프레임 df의 경우 데이터를 탐색하는 동안 사용되는 인쇄 된 쉼표 형식의 행 수 :

def nrow(df):
    print("{:,}".format(df.shape[0]))

예:

nrow(my_df)
12,456,789

참고 URL : https://stackoverflow.com/questions/15943769/how-do-i-get-the-row-count-of-a-pandas-dataframe

반응형