首页 > 解决方案 > 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

标签: pythonpandasdataframeif-statement

解决方案


首先对于测试缺失值是必要的Series.isna,然后可以通过Series.eqfor进行比较==并通过以下方式设置值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

推荐阅读