Passing column name to python function


I have created a function that does something like this that accepts a pandas dataframe and a column name.

def summaryTable(df, cutoff, column):
    if cutoff == 1:
        df[column] = df.column.astype(str)

When I do this I get an AttributeError, DataFrame object has no attribute ‘column’. Is there a way to pass a column to a function and refer to it in this manner? There are other things happening in my actual function but wanted to simplify it down to the part I’m having issues with if this seems like a strange function.

>Solution :

Just use [ ] for access and assignment, consider following simple example

import pandas as pd
df = pd.DataFrame({"col1":[1,2,3]})
def make_float(df, column_name):
    df[column_name] = df[column_name].astype(float)
make_float(df, "col1")

gives output

0   1.0
1   2.0
2   3.0

Leave a Reply Cancel reply