【问题标题】:pandas.DataFrame.apply() produces NaN when filtering with square bracketspandas.DataFrame.apply() 使用方括号过滤时产生 NaN
【发布时间】:2018-07-17 09:55:35
【问题描述】:
import pandas as pd
df = pd.DataFrame({"First_Column": [-2,-1,1,2,3]})
df['Second_Column']='Good'
df.loc[:, 'Second_Column']=df[df.First_Column>0]['Second_Column'].apply(lambda x: 'Bad')

当我运行它时,我在Second_Column 中得到BadNaN,而不是GoodBad。为什么apply() 会用NaN 覆盖不符合条件的值?

【问题讨论】:

    标签: python pandas dataframe nan


    【解决方案1】:

    通过使用mask

    df.Second_Column=df.Second_Column.mask(df.First_Column>0,'Bad')
    df
    Out[441]: 
       First_Column Second_Column
    0            -2          Good
    1            -1          Good
    2             1           Bad
    3             2           Bad
    4             3           Bad
    

    或者

    df.loc[df.First_Column>0,'Second_Column']='Bad'
    df
    Out[443]: 
       First_Column Second_Column
    0            -2          Good
    1            -1          Good
    2             1           Bad
    3             2           Bad
    4             3           Bad
    

    或者使用np.where更直接

    df['Second_Column']=np.where(df.First_Column>0,'Bad','Good')
    df
    Out[445]: 
       First_Column Second_Column
    0            -2          Good
    1            -1          Good
    2             1           Bad
    3             2           Bad
    4             3           Bad
    

    【讨论】:

    • 有没有办法使用mask () 或上述任何方法来处理多个条件?我尝试使用|,但它不起作用。
    • @PrincyPrincy 你应该看看np.select :-)
    • 一开始我放弃的太早了,赶紧去问问。经过更多的试验和错误,它起作用了:| 和大概&mask() 一起工作得很好。谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-22
    相关资源
    最近更新 更多