Consider:
In [35]: test = pd.DataFrame({'a':range(4),'b':range(4,8)})
In [36]: test
Out[36]:
a b
0 0 4
1 1 5
2 2 6
3 3 7
In [37]: for i in test['a']:
....: print i
....:
0
1
2
3
In [38]: for i,j in test:
....: print i,j
....:
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
ValueError: need more than 1 value to unpack
In [39]: for i,j in test[['a','b']]:
....: print i,j
....:
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
ValueError: need more than 1 value to unpack
In [40]: for i,j in [test['a'],test['b']]:
....: print i,j
....:
------------------------------------------------------------
Traceback (most recent call last):
File "<ipython console>", line 1, in <module>
ValueError: too many values to unpack
In order to iterate over rows, we use iteritems() function this function iterates over each column as key, value pair with the label as key, and column value as a Series object. Code #1: Python3.
DataFrame. iterrows() method is used to iterate over DataFrame rows as (index, Series) pairs. Note that this method does not preserve the dtypes across rows due to the fact that this method will convert each row into a Series .
Using iterrows() method to iterate rows The iterrows() method is used to iterate over the rows of the pandas DataFrame. It returns a tuple which contains the row index label and the content of the row as a pandas Series. # Iterate over the row values using the iterrows() method for ind, row in df.
Vectorization is always the first and best choice. You can convert the data frame to NumPy array or into dictionary format to speed up the iteration workflow. Iterating through the key-value pair of dictionaries comes out to be the fastest way with around 280x times speed up for 20 million records.
Use the DataFrame.itertuples() method:
for a, b in test.itertuples(index=False):
print a, b
You can use zip
(this is native in Python 3 and can be imported from itertools
as izip
in Python 2.7):
for a,b in zip(test.a, test.b):
print(a,b)
for a,b in izip(test.a, test.b):
print a,b
Try,
for i in test.index : print test['a'][i], test['b'][i]
to give you,
0 4
1 5
2 6
3 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With