Dataframe.apply row type

Viewed 75

Given a sample dataframe:

import pandas as pd

d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(d)

If the user wants to create a new column based on previous columns, they could create a function (it could also be a lambda function, but for this example a reguar function is used.

def calc_new_column(row):
    ''' creates new column based on values from other columns
    
    args:
        row: the rows of a pandas dataframe
    
    return: value that goes into each row of the new coulmn of the dataframe

    '''
    # print(type(row))

    if int(row['col1']) > 1:
        if int(row['col2']) <= 5:
            return 'in range'
    return 'out range'

Finally, the user can apply this function to all the rows on the dataframe creating the new column.

# the new column
df['col3'] = df.apply(calc_new_column, axis=1)

This successfully produces the new column. (output)

   col1  col2       col3
0     1     4  out range
1     2     5   in range
2     3     6  out range

If one does type(row) the result is <class 'pandas.core.series.Series'>, but one cannot type hint to this.

So the question is, what is the type of the argument row that is input into the funciton (that one might indicate to the user with type hinting or in the doc string)?

0 Answers
Related