Pandas - 熊猫默认情况下

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/49228596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:18:29  来源:igfitidea点击:

Pandas - Case when & default in pandas

pythonpandas

提问by Tom J Muthirenthi

I have the below case statement in python,

我在python中有以下case语句,

pd_df['difficulty'] = 'Unknown'
pd_df['difficulty'][(pd_df['Time']<30) & (pd_df['Time']>0)] = 'Easy'
pd_df['difficulty'][(pd_df['Time']>=30) & (pd_df['Time']<=60)] = 'Meduim'
pd_df['difficulty'][pd_df['Time']>60] = 'Hard'

But when I run the code, it throws an error.

但是当我运行代码时,它会引发错误。

A value is trying to be set on a copy of a slice from a DataFrame

回答by cs95

Option 1
For performance, use a nested np.wherecondition. For the condition, you can just use pd.Series.between, and the default value will be inserted accordingly.

选项 1
为了提高性能,请使用嵌套np.where条件。对于条件,您可以使用pd.Series.between,并相应地插入默认值。

pd_df['difficulty'] = np.where(
     pd_df['Time'].between(0, 30, inclusive=False), 
    'Easy', 
     np.where(
        pd_df['Time'].between(0, 30, inclusive=False), 'Medium', 'Unknown'
     )
)


Option 2
Similarly, using np.select, this gives more room for adding conditions:

选项 2
同样,使用np.select,这为添加条件提供了更多空间:

pd_df['difficulty'] = np.select(
    [
        pd_df['Time'].between(0, 30, inclusive=False), 
        pd_df['Time'].between(30, 60, inclusive=True)
    ], 
    [
        'Easy', 
        'Medium'
    ], 
    default='Unknown'
)


Option 3
Another performant solution involves loc:

选项 3
另一种高性能解决方案包括loc

pd_df['difficulty'] = 'Unknown'
pd_df.loc[pd_df['Time'].between(0, 30, inclusive=False), 'difficulty'] = 'Easy'
pd_df.loc[pd_df['Time'].between(30, 60, inclusive=True), 'difficulty'] = 'Medium'