python - DF中2列得到3列的条件
问题描述
我想创建一个 IF 条件来设置新列('new_col')中的值。总体思路是这样的:
如果'分数' = np.nan & '年份' = 2012:返回 1
elif 'Score' == np.nan & 'Year' = 2013:返回 2
否则:返回“分数”
data = {'year': [2010, 2011, 2012, 2013, 2014], 'Score': [10, 15, np.nan, np.nan, 3]}
df = pd.DataFrame(data, columns = ['year', 'Score'])
year Score
0 2010 10.0
1 2011 15.0
2 2012 1.0
3 2013 2.0
4 2014 3.0
解决方案
首先对于测试缺失值是必要的Series.isna
,然后可以通过Series.eq
for进行比较==
并通过以下方式设置值numpy.select
:
m1 = df['Score'].isna() & df['year'].eq(2012)
m2 = df['Score'].isna() & df['year'].eq(2013)
df['Score'] = np.select([m1, m2], [1,2], default=df['Score'])
print (df)
year Score
0 2010 10.0
1 2011 15.0
2 2012 1.0
3 2013 2.0
4 2014 3.0
对于新列使用:
df['new_col'] = np.select([m1, m2], [1,2], default=df['Score'])
print (df)
year Score new_col
0 2010 10.0 10.0
1 2011 15.0 15.0
2 2012 NaN 1.0
3 2013 NaN 2.0
4 2014 3.0 3.0
推荐阅读
- hibernate - 从多对多关系中检索的 HQL 语法
- javascript - not able to target required data with jquery
- php - Yii2 Swift_SmtpTransport gmail 不工作
- mysql - 使用 MySQL 中的某些 JSON 列加载查询得到 {Invalid JSON text: "Invalid value." 在列 } 值的位置 0
- jquery - 在执行单击操作之前,jquery 脚本不起作用
- angular - 标头未发送 angular-5
- java - Java Map 的 RAML 1.0 表示
- ios - 数据验证完成后如何移动到第二个 ViewController
- firebase - 使用 Firebase 中的多个值检索 id
- ionic-framework - 如何在 ionic 3 中扫描 iBeacon?