Passing column name to python function

Question:

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.

Asked By: user2355903

||

Answers:

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")
print(df)

gives output

   col1
0   1.0
1   2.0
2   3.0
Answered By: Daweo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.