如何将用户字符串输入转换为条件以作为参数传递给 Python Pandas' drop 函数?
How to convert user-string-input into conditions to pass as parameters to Python Pandas' drop function?
在pandas中如果你想根据条件删除一些行,你可以这样做:
df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
主要的变化部分是以下表示条件的部分:
(df.score < 50) & (df.score > 20)
我正在尝试基于此创建自己的函数。
def drop_condition(df, cond_in_str):
df.drop(df[cond_in_str].index, inplace=True)
并这样称呼它:
drop_condition(df, 'df.score < 50')
KeyError: 'df.score < 50'
如何将条件字符串转换为 Pandas drop 函数可以识别的参数条件?
创建另一个变量并赋值给它怎么样?然后在函数中使用
check_val = df.score > 50
(drop_condition(df, check_val))
您需要使用 pandas.DataFrame.query() 将表达式作为 string
.
def drop_condition(df, cond_in_str):
df.drop(df.query(cond_in_str).index)
您可以按原样使用您的函数,只是没有引号:
drop_condition(df, df.score < 50)
在pandas中如果你想根据条件删除一些行,你可以这样做:
df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
主要的变化部分是以下表示条件的部分:
(df.score < 50) & (df.score > 20)
我正在尝试基于此创建自己的函数。
def drop_condition(df, cond_in_str):
df.drop(df[cond_in_str].index, inplace=True)
并这样称呼它:
drop_condition(df, 'df.score < 50')
KeyError: 'df.score < 50'
如何将条件字符串转换为 Pandas drop 函数可以识别的参数条件?
创建另一个变量并赋值给它怎么样?然后在函数中使用
check_val = df.score > 50
(drop_condition(df, check_val))
您需要使用 pandas.DataFrame.query() 将表达式作为 string
.
def drop_condition(df, cond_in_str):
df.drop(df.query(cond_in_str).index)
您可以按原样使用您的函数,只是没有引号:
drop_condition(df, df.score < 50)