• Home
  • Django
  • using iterrows() and itertuples() in pandas

using iterrows() and itertuples() in pandas

linkaiyi
Follow

itertuples() in dataframe

return of itertuples() is namedtuple. Items of namedtuple can be accessed like item.A (A is the column name) or accessed like item[‘A’] after converting namedtuple to dictionary. important column name will be changed to ‘_number’ if column name contains space or “.”. Because these kind of column name cannot be accessed in namedtuple.

example:

for row in df.itertuples():
    print(row.A)
    print(row.Index) # first item of row is always index

iterrows() in dataframe

return of iterrows() is index and row as dictionary

example:

for index, row in df.iterrows():
    print(row[A])
    print(index)

itertuples() is much faster than iterrows()

```python
df = pd.DataFrame([x for x in range(1000*1000)], columns=[‘A’])
st=time.time()
for index, row in df.iterrows():
row.A
print(time.time()-st)
45.05799984931946

st=time.time()
for row in df.itertuples():
row.A
print(time.time() - st)
0.48400020599365234
``

Object has 0 attachments

Was this article helpful?

This article is viewed 18 times!

0 Comments

Leave a Comment

Support