Pandas DataFrame | iterrows method
Start your free 7-days trial now!
Pandas DataFrame.iterrows()
method is used to iterate over all pairs of row name (object
) and row values (Series
) in the source DataFrame.
Parameters
The method iterrows()
does not take any parameters.
Return value
An iterator of row_name
(object
) and content
(Series
).
Do not modify row_name
and content
within the loop, as the source DataFrame may or may not be modified.
Examples
Basic usage
Consider the following DataFrame:
df
A B0 a c1 b d
To iterate over the rows:
Forced casting
The iterrows(~)
method return row values as a Series
. This can be a problem when your row values contain multiple data types since Series
can only hold one data type. To account for this, iterrows()
picks a data type that can accommodate all the row values.
For instance, consider the following DataFrame:
df
A B0 1 3.01 2 4.0
Here, the first column is of type int
, while the second column is of type float
.
We iterate over the rows:
Notice how the values corresponding to column A
was casted from int
to float
. This is because float
is more general than int
.