简体   繁体   English

pandas.DataFrame.apply()使用方括号过滤时会产生NaN

[英]pandas.DataFrame.apply() produces NaN when filtering with square brackets

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')

When I run this I get Bad and NaN in the Second_Column , instead of Good and Bad . 当我运行它时,我在Second_Column得到BadNaN ,而不是GoodBad Why does apply() overwrite the values that didn't meet the criteria with NaN ? 为什么apply()NaN覆盖不符合条件的值?

By using mask 通过使用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

Or 要么

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

Or using np.where more straightforward 或者使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM