问题描述
我有这个函数来清理我的输入表(因为我有多个表需要这种处理,所以我决定编写这个函数)。
参数'table'是我们输入的pandas DataFrame,而'control_list'只是验证我们是否要执行转换。
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
使用它的例子是:
input_formatting(some_df,[1,1,1])
我的问题是,有人可以推荐一种更 Pythonic/优雅的方式来编写 if-else-pass 语句吗?这似乎不必要地冗长和冗长。
谢谢!
解决方法
else
在 if-else 中是可选的,即:
if True:
print("True")
else:
pass
可以用更简洁的方式写成
if True:
print("True")
help("if")
确实说
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
注意如果存在在最后一句中。