search
Search
Login
Unlock 100+ guides
menu
menu
web
search toc
close
Comments
Log in or sign up
Cancel
Post
account_circle
Profile
exit_to_app
Sign out
What does this mean?
Why is this true?
Give me some examples!
search
keyboard_voice
close
Searching Tips
Search for a recipe:
"Creating a table in MySQL"
Search for an API documentation: "@append"
Search for code: "!dataframe"
Apply a tag filter: "#python"
Useful Shortcuts
/ to open search panel
Esc to close search panel
to navigate between search results
d to clear all current filters
Enter to expand content preview
icon_star
Doc Search
icon_star
Code Search Beta
SORRY NOTHING FOUND!
mic
Start speaking...
Voice search is only supported in Safari and Chrome.
Navigate to

Pandas DataFrame | iterrows method

schedule Aug 10, 2023
Last updated
local_offer
PythonPandas
Tags
mode_heat
Master the mathematics behind data science with 100+ top-tier guides
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).

WARNING

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 = pd.DataFrame({"A":["a","b"],"B":["c","d"]})
df
   A  B
0  a  c
1  b  d

To iterate over the rows:

for row_name, content in df.iterrows():
   print("row_name:", row_name)
   print(content)
row_name: 0
A a
B c
Name: 0, dtype: object
row_name: 1
A b
B d
Name: 1, dtype: object

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 = pd.DataFrame({"A":[1,2],"B":[3.0,4.0]})
df
   A  B
0  1  3.0
1  2  4.0

Here, the first column is of type int, while the second column is of type float.

We iterate over the rows:

for row_name, content in df.iterrows():
   print("row_name:", row_name)
   print(content)
row_name: 0
A 1.0
B 3.0
Name: 0, dtype: float64
row_name: 1
A 2.0
B 4.0
Name: 1, dtype: float64

Notice how the values corresponding to column A was casted from int to float. This is because float is more general than int.

robocat
Published by Isshin Inada
Edited by 0 others
Did you find this page useful?
thumb_up
thumb_down
Comment
Citation
Ask a question or leave a feedback...
thumb_up
1
thumb_down
0
chat_bubble_outline
0
settings
Enjoy our search
Hit / to insta-search docs and recipes!