Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

gives output

   col1
0   1.0
1   2.0
2   3.0
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading