【问题标题】:np.where() do nothing if condition fails如果条件失败,np.where() 什么也不做
【发布时间】:2019-01-17 19:54:27
【问题描述】:

我的数据框中有一个样本:

       Created      Insert Time   MatchKey              In Previous    New Type
18593  2016-08-12   2018-02-19    LXGS090393APIN040640       No        New Existing
5517   2016-08-12   2018-02-19    LIN380076CI166203726       No        New Existing
2470   2018-02-12   2018-02-19    CI164414649APIN160672      No        New Existing
13667  2016-08-12   2018-02-19    LIN257400APIN015446       Yes        New Existing
10998  2016-08-12   2018-02-19    LXSV225786APIN158860      Yes        New Existing
20149  2016-08-12   2018-02-19    LIN350167APIN158284       Yes        New Existing
20143  2016-08-12   2018-02-19    LIN350167APIN161348       Yes        New Existing
30252  2016-08-12   2018-02-19    LXGS120737APIN153339      Yes        New Existing
12583  2016-08-09   2018-02-19    WIN556410APIN157186       Yes        New Existing
28591  2018-05-03   2018-02-19    CI195705185APIN009076      No        New Created

我想替换 New Type 列中的值,如果条件失败,该函数不执行任何操作:

current['New Type'] = np.where(current['In Previous']=='Yes','In Previous',pass)

但显然它会导致语法错误,因为 np.where() 不处理 pass:

File "<ipython-input-9-7f68cda12cbe>", line 1
current['New Type'] = np.where(current['In Previous']=='Yes','In Previous',pass)

                                                                          ^
SyntaxError: invalid syntax

有什么替代方法可以达到同样的效果?

【问题讨论】:

  • where 不是 if/else 克隆。

标签: python python-3.x pandas numpy


【解决方案1】:

只返回列而不是pass,这与条件为False时什么都不做一样:

current['New Type'] = np.where(current['In Previous']=='Yes','In Previous',current['New Type'] )

或者您可以只屏蔽这些行:

current['New Type'] = current.loc[current['In Previous']=='Yes', 'In Previous']

【讨论】:

    【解决方案2】:

    您可以将pd.Series.mask 用于此目的:

    df['New Type'].mask(df['In Previous']=='Yes', 'In Previous', inplace=True)
    

    有点令人困惑的是,您必须记住pd.Series.mask 在满足条件时更新值,而pd.Series.where 在条件满足时更新值。

    【讨论】:

    • 我有 TypeError: mask() got multiple values for argument 'inplace'。为什么?
    猜你喜欢
    • 2016-10-27
    • 2015-01-24
    • 1970-01-01
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多