Coding Ref

How to use intertuples() in Pandas

How to use intertuples() in Pandas

The itertuples() function in Pandas is used to iterate over the rows of a dataframe as tuples.

This is often used to perform an operation on each row of a dataframe, without the overhead of creating a new DataFrame or series for each row.

Here's an example of using the itertuples() function in Pandas:

main.py
import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({"A": [1, 2, 3, 4, 5],
                   "B": [6, 7, 8, 9, 10]})

# iterate over the rows of the DataFrame as tuples
for row in df.itertuples():
    print(row)

This will iterate over the rows of the DataFrame as tuples, and print each row to the console. The output will be:

output
Pandas(Index=0, A=1, B=6)
Pandas(Index=1, A=2, B=7)
Pandas(Index=2, A=3, B=8)
Pandas(Index=3, A=4, B=9)
Pandas(Index=4, A=5, B=10)

Performing an operation on each row of the DataFrame

You can also use the itertuples() function to perform an operation on each row of the DataFrame.

This function returns an iterator that yields a namedtuple for each row of the dataframe, with the columns of the row as elements of the namedtuple.

This allows you to access the data in each row of the dataframe and perform an operation on it.

For example:

main.py
import pandas as pd

# create a sample dataframe
df = pd.DataFrame({'A': [1, 2, 3],
                   'B': [4, 5, 6],
                   'C': [7, 8, 9]})

# iterate over the rows of the dataframe
for row in df.itertuples():
    # access the data in each column of the row
    col_a = row.A
    col_b = row.B
    col_c = row.C

    # perform an operation on the data in the row
    result = col_a + col_b + col_c

    # print the result
    print(result)
output
12
15
18

For each row, the code accesses the data in each column of the row using the namedtuple returned by itertuples().

The code then performs an operation on the data in the row by adding the values in columns A, B, and C together.

Finally, the code prints the result of the operation for each row.

You'll also like

Related tutorials curated for you

    What does factorize() do in Pandas?

    How to concatenate in Pandas

    How to fix: ValueError: pandas cannot reindex from a duplicate axis

    How to normalize a column in Pandas

    How to convert a series to a list in Pandas

    How to use ewm() in Pandas

    Pandas read SQL

    How to find the mode in a Pandas DataFrame

    How to use str.contains() in Pandas

    How to join two DataFrames in Pandas

    What is idxmax() in Pandas?

    How to read a TSV file in Pandas