Reputation: 21
I have this function that cleans my input tables (since I have multiple tables that need this treatment, I decided to write this function).
The parameter 'table' is our input pandas DataFrame while 'control_list' is just a verification whether we want to perform the transformation.
def input_formatting(table, control_list):
#drop rows with NA's
if control_list[0] == 1:
table.dropna(inplace = True, how = 'all')
else:
pass
#change all column names to lower case
if control_list[1] == 1:
table.columns = table.columns.str.lower()
else:
pass
#remove all whitespace in column names
if control_list[2] == 1:
table.rename(columns=lambda x: x.strip(), inplace = True)
else:
pass
#change all spaces to _ in col names
if control_list[3] == 1:
table.rename(columns=lambda x: x.replace(' ','_'), inplace = True)
else:
pass
Example of using this would be:
input_formatting(some_df, [1,1,1,1])
My question is, can someone recommend a more Pythonic / elegant way of writing the if-else-pass statement? It seems unnecessarily verbose and long.
Thanks!
Upvotes: 0
Views: 90
Reputation: 36510
else
is optional in if-else i.e.:
if True:
print("True")
else:
pass
might be written in more concise way as
if True:
print("True")
help("if")
does says
The "if" statement
******************
The "if" statement is used for conditional execution:
if_stmt ::= "if" expression ":" suite
("elif" expression ":" suite)*
["else" ":" suite]
It selects exactly one of the suites by evaluating the expressions one
by one until one is found to be true (see section Boolean operations
for the definition of true and false); then that suite is executed
(and no other part of the "if" statement is executed or evaluated).
If all expressions are false, the suite of the "else" clause, if
present, is executed.
Related help topics: TRUTHVALUE
Note if present in last sentence.
Upvotes: 3