Function: Finding Col names from a DataFrame

Question:

This is the error I am getting:
SyntaxError: invalid syntax

I am attempting to pass the variable dataname to the function Colnames so that it will return the names of the columns for the respective dataframe. I want to display an error message on invalid user input but the I am screwing up the syntax. I think the logic should be okay? I have tried the If statement with and without the parentheses

def Colnames(dataname):
If (dataname == 'df1'):
    data_cols = df1.columns
Elif (dataname == 'df2'):
    data_cols = df2.columns
Else:
   tk.messagebox.showerror('Error: User Input. Please Enter df1 or df2')
return print(data_cols)

Should return column names of df1 with Colnames(df1).

If you have any thoughts please advise. Thanks

Asked By: arblu3

||

Answers:

You have some indentation and casing issues there – this should work:

def Colnames(dataname):
    if (dataname == 'df1'):
        data_cols = df1.columns
    elif (dataname == 'df2'):
        data_cols = df2.columns
    else:
        tk.messagebox.showerror('Error: User Input. Please Enter df1 or df2')
    return data_cols
Answered By: James_SO
def Colnames(dataname):
    if dataname == 'df1':
        data_cols = df1.columns
        for i in data_cols: 
            print(i)
    elif dataname == 'df2':
        data_cols = df2.columns
        for i in data_cols: 
            print(i)
    else:
        print('Error: User Input. Please Enter df1 or df2')
    return
Colnames('df1')
Answered By: arblu3
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.