Jak uzyskać liczbę wierszy ramki danych Pandy?
Próbuję zdobyć liczbę wierszy dataframe df z pand, a oto mój kod.
Metoda 1:
total_rows = df.count
print total_rows +1
Metoda 2:
total_rows = df['First_columnn_label'].count
print total_rows +1
Oba fragmenty kodu dają mi ten błąd:
Co robię źle?TypeError: nieobsługiwane typy operandów dla +: 'instancemethod' i ' int '
Zgodnie z odpowiedzią udzieloną przez @ root najlepszym (najszybszym) sposobem sprawdzenia długości df jest wywołanie:
df.shape[0]
12 answers
Możesz użyć właściwości .shape
lub po prostu len(DataFrame.index)
. Istnieją jednak znaczące różnice w wydajności (len(DataFrame.index)
jest najszybsza):
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)
EDIT: jak @Dan Allen zauważył w komentarzach len(df.index)
i df[0].count()
nie są wymienne, ponieważ count
wyklucza NaN
s,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-18 05:29:34
Załóżmy, że df
jest ramką danych wtedy:
count_row = df.shape[0] # gives number of row count
count_col = df.shape[1] # gives number of col count
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-27 20:51:45
Użyj len(df)
. Działa to od pandy 0.11, A może nawet wcześniej.
__len__()
jest obecnie (0.12) udokumentowane Returns length of index
. Informacje o czasie, skonfiguruj tak samo jak w odpowiedzi roota:
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
Ze względu na jedno dodatkowe wywołanie funkcji jest nieco wolniejsze niż wywołanie bezpośrednio len(df.index)
, ale w większości przypadków nie powinno to odgrywać żadnej roli.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-08-19 15:10:16
Oprócz powyższych odpowiedzi można użyć df.axes
, Aby uzyskać krotkę z indeksami wierszy i kolumn, a następnie użyć funkcji len()
:
total_rows=len(df.axes[0])
total_cols=len(df.axes[1])
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-19 19:28:21
Aby uzyskać wiersze, użyj
df.index
I dla kolumn, użyj
df.columns
Zawsze możesz użyć len(anyList)
do uzyskania liczenia listy, stąd możesz użyć
len(df.index)
dla uzyskania liczby wierszy, lub krótszy spróbuj {[4] } dla liczby wierszy.
Alternatywnie możesz użyć df.shape[0] and df.shape[1]
do uzyskania odpowiednio liczby wierszy i kolumn.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-08-09 14:41:23
Przychodzę do pand z tła R
i widzę, że pandy są bardziej skomplikowane, jeśli chodzi o wybór wiersza lub kolumny.
Musiałem się z nim przez jakiś czas zmagać, potem znalazłem kilka sposobów na poradzenie sobie:
Uzyskanie liczby kolumn:
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.
Uzyskanie liczby wierszy:
len(df.index) #It's similar.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-29 07:41:41
...bazując na odpowiedzi Jana-Filipa Gehrcke.
Powód, dla którego len(df)
lub len(df.index)
jest szybszy niż df.shape[0]
. Spójrz na kod. df.shape jest @property
, który uruchamia metodę DataFrame wywołującą len
dwukrotnie.
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)
I pod maską Lena (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)
będzie nieco szybszy niż len(df)
, ponieważ ma o jedno wywołanie funkcji mniej, ale zawsze jest szybszy niż df.shape[0]
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-12-07 23:37:11
df.shape
zwraca Kształt ramki danych w postaci krotki (no. rzędów, nie cols).
Możesz po prostu uzyskać dostęp do no. rzędów lub nie. cols z df.shape[0]
lub df.shape[1]
, odpowiednio, co jest takie samo jak dostęp do wartości krotki.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-06 13:25:21
Liczba wierszy (użyj dowolnego z):
df.shape[0]
len(df)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-20 08:56:29
Jeśli chcesz uzyskać liczbę wierszy w środku operacji łańcuchowej, możesz użyć:
df.pipe(len)
Przykład:
row_count = (
pd.DataFrame(np.random.rand(3,4))
.reset_index()
.pipe(len)
)
Może to być użyteczne, jeśli nie chcesz umieszczać długich instrukcji wewnątrz funkcji len ().
Możesz użyć _ _ len _ _ () zamiast tego, ale__ len _ _ () wygląda trochę dziwnie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-22 02:58:24
Dla dataframe df, drukowana liczba wierszy sformatowanych przecinkami używana podczas eksploracji danych:
def nrow(df):
print("{:,}".format(df.shape[0]))
Przykład:
nrow(my_df)
12,456,789
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-21 01:59:14
Łatwo jedna linia
your_data _frame.shape
Da Ci prostą liczbę wierszy i kolumn
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-17 23:52:08