Jak iterować wiersze w ramce danych w pandach?

Mam DataFrame od pandy:

import pandas as pd
inp = [{'c1':10, 'c2':100}, {'c1':11,'c2':110}, {'c1':12,'c2':120}]
df = pd.DataFrame(inp)
print df

Wyjście:

   c1   c2
0  10  100
1  11  110
2  12  120

Teraz chcę iterować po rzędach tej ramki. Dla każdego wiersza chcę mieć dostęp do jego elementów (wartości w komórkach) po nazwie kolumn. Na przykład:

for row in df.rows:
   print row['c1'], row['c2']
Czy można to zrobić w pandach?

Znalazłem to podobne pytanie. Ale to nie daje mi odpowiedzi, której potrzebuję. Na przykład sugeruje się tam użycie:

for date, row in df.T.iteritems():

Lub

for row in df.iterrows():

Ale ja nie zrozum, czym jest obiekt row i jak mogę z nim pracować.

Author: petezurich, 2013-05-10

14 answers

Iterrows jest generatorem, który daje zarówno indeks, jak i wiersz

for index, row in df.iterrows():
   print row['c1'], row['c2']

Output: 
   10 100
   11 110
   12 120
 1225
Author: waitingkuo,
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-13 13:57:37

Do iteracji przez wiersz DataFrame w pandach można użyć:

itertuples() ma być szybszy niż iterrows()

Ale należy pamiętać, zgodnie z docs (pandy 0.21.1 w tej chwili):

  • Iterrows: dtype może nie pasować od wiersza do wiersza

    Ponieważ iterrows zwraca szereg dla każdego wiersza, to nie preserve dtypy w wierszach (dtypy są zachowywane w kolumnach dla ramek danych).

  • Iterrows: nie modyfikuj wierszy

    Powinieneśnigdy nie modyfikować czegoś, nad czym pracujesz. Nie gwarantuje to działania we wszystkich przypadkach. W zależności od typów danych iterator zwraca kopię, a nie Widok, a zapis do niego nie będzie miał żadnego efektu.

    Użyj Ramki Danych .apply () zamiast:

    new_df = df.apply(lambda x: x * 2)
    
  • Itertuples:

    Nazwy kolumn zostaną zmienione na nazwy pozycyjne, jeśli są nieprawidłowymi identyfikatorami Pythona, powtarzane lub zaczynają się od podkreślenia. Przy dużej liczbie kolumn (>255) zwracane są zwykłe krotki.

 174
Author: viddik13,
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-17 03:54:27

Chociaż iterrows() jest dobrym rozwiązaniem, czasami itertuples() może być znacznie szybsze:

df = pd.DataFrame({'a': randn(1000), 'b': randn(1000),'N': randint(100, 1000, (1000)), 'x': 'x'})

%timeit [row.a * 2 for idx, row in df.iterrows()]
# => 10 loops, best of 3: 50.3 ms per loop

%timeit [row[1] * 2 for row in df.itertuples()]
# => 1000 loops, best of 3: 541 µs per loop
 124
Author: e9t,
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-06-01 09:00:01

Możesz również użyć df.apply() do iteracji wierszy i dostępu do wielu kolumn dla funkcji.

Docs: DataFrame.Zastosuj()

def valuation_formula(x, y):
    return x * y * 0.5

df['price'] = df.apply(lambda row: valuation_formula(row['x'], row['y']), axis=1)
 67
Author: cheekybastard,
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-06-01 06:24:44

Możesz użyć df.funkcja iloc w następujący sposób:

for i in range(0, len(df)):
    print df.iloc[i]['c1'], df.iloc[i]['c2']
 53
Author: PJay,
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-07 09:09:10

Szukałem Jak iterować na wierszach i kolumnach i skończyło się tutaj tak:

for i, row in df.iterrows():
    for j, column in row.iteritems():
        print(column)
 16
Author: Lucas B,
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-01-17 09:41:29

Użyj itertuples () . Jest szybszy niż iterrows():

for row in df.itertuples():
    print "c1 :",row.c1,"c2 :",row.c2
 14
Author: Nurul Akter Towhid,
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-07-27 16:32:32

Aby zapętlić wszystkie wiersze w dataframe możesz użyć:

for x in range(len(date_example.index)):
    print date_example['Date'].iloc[x]
 12
Author: Pedro Lobito,
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-04-04 20:46:53

Możesz napisać swój własny iterator, który implementuje namedtuple

from collections import namedtuple

def myiter(d, cols=None):
    if cols is None:
        v = d.values.tolist()
        cols = d.columns.values.tolist()
    else:
        j = [d.columns.get_loc(c) for c in cols]
        v = d.values[:, j].tolist()

    n = namedtuple('MyTuple', cols)

    for line in iter(v):
        yield n(*line)

Jest to bezpośrednio porównywalne z pd.DataFrame.itertuples. Staram się wykonywać to samo zadanie z większą wydajnością.


Dla podanego dataframe z moją funkcją:

list(myiter(df))

[MyTuple(c1=10, c2=100), MyTuple(c1=11, c2=110), MyTuple(c1=12, c2=120)]

Lub z pd.DataFrame.itertuples:

list(df.itertuples(index=False))

[Pandas(c1=10, c2=100), Pandas(c1=11, c2=110), Pandas(c1=12, c2=120)]

Kompleksowy test
Testujemy udostępnianie wszystkich kolumn i ich podzbiory.

def iterfullA(d):
    return list(myiter(d))

def iterfullB(d):
    return list(d.itertuples(index=False))

def itersubA(d):
    return list(myiter(d, ['col3', 'col4', 'col5', 'col6', 'col7']))

def itersubB(d):
    return list(d[['col3', 'col4', 'col5', 'col6', 'col7']].itertuples(index=False))

res = pd.DataFrame(
    index=[10, 30, 100, 300, 1000, 3000, 10000, 30000],
    columns='iterfullA iterfullB itersubA itersubB'.split(),
    dtype=float
)

for i in res.index:
    d = pd.DataFrame(np.random.randint(10, size=(i, 10))).add_prefix('col')
    for j in res.columns:
        stmt = '{}(d)'.format(j)
        setp = 'from __main__ import d, {}'.format(j)
        res.at[i, j] = timeit(stmt, setp, number=100)

res.groupby(res.columns.str[4:-1], axis=1).plot(loglog=True);

Tutaj wpisz opis obrazka

Tutaj wpisz opis obrazka

 12
Author: piRSquared,
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-07 04:29:57

IMHO, najprostsza decyzja

 for ind in df.index:
     print df['c1'][ind], df['c2'][ind]
 8
Author: Grag2015,
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-02 10:33:40

Aby zapętlić wszystkie wiersze w dataframe i użyj wartości każdego wiersza wygodnie, namedtuples można przekonwertować na ndarray s. na przykład:

df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]}, index=['a', 'b'])

Iteracja nad wierszami:

for row in df.itertuples(index=False, name='Pandas'):
    print np.asarray(row)

Wyniki w:

[ 1.   0.1]
[ 2.   0.2]

Należy pamiętać, że jeśli index=True, indeks jest dodawany jako pierwszy element krotki , co może być niepożądane dla niektórych aplikacji.

 4
Author: KutalmisB,
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-04-24 08:48:05

Dodając do powyższych odpowiedzi, czasami użyteczny wzór to:

# Borrowing @KutalmisB df example
df = pd.DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2]}, index=['a', 'b'])
# The to_dict call results in a list of dicts
# where each row_dict is a dictionary with k:v pairs of columns:value for that row
for row_dict in df.to_dict(orient='records'):
    print(row_dict)

Co daje:

{'col1':1.0, 'col2':0.1}
{'col1':2.0, 'col2':0.2}
 3
Author: Zach,
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-06-27 18:48:28

Po co komplikować sprawy?

Proste.

import pandas as pd
import numpy as np

# Here is an example dataframe
df_existing = pd.DataFrame(np.random.randint(0,100,size=(100, 4)), columns=list('ABCD'))

for idx,row in df_existing.iterrows():
    print row['A'],row['B'],row['C'],row['D']
 2
Author: Justin Malinchak,
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-07-10 15:05:42

Możesz również zrobić numpy indeksowanie dla jeszcze większych przyspieszeń. To nie jest naprawdę iteracja, ale działa znacznie lepiej niż iteracja dla niektórych aplikacji.

subset = row['c1'][0:5]
all = row['c1'][:]

Możesz też wrzucić go do tablicy. Te indeksy / selekcje mają już działać jak tablice Numpy, ale napotkałem problemy i musiałem rzucić

np.asarray(all)
imgs[:] = cv2.resize(imgs[:], (224,224) ) #resize every image in an hdf5 file
 1
Author: James L.,
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-01 18:22:38