如何根据python中行值的条件在列中应用值

时间:2017-12-07 06:53:15

标签: python pandas datetime dataframe merge

我有一个如下所示的数据框:

DF

    Name        year    week    date
0   Adam        2016    16  2016-04-24
1   Mary        2016    17  2016-05-01
2   Jane        2016    20  2016-05-22
3   Joe         2016    17  2016-05-01
4   Arthur      2017    44  2017-11-05   
5   Liz         2017    41  2017-10-15
6   Janice      2016    47  2016-11-27

我想创建列季节df['season'],根据MAM中的值,定义季节ONDweek

结果应如下所示:

df_final

    Name        year    week    date      season
0   Adam        2016    16      2016-04-24 MAM
1   Mary        2016    17      2016-05-01 MAM
2   Jane        2016    20      2016-05-22 MAM
3   Joe         2016    17      2016-05-01 MAM
4   Arthur      2017    44      2017-11-05 OND 
5   Liz         2017    41      2017-10-15 OND
6   Janice      2016    47      2016-11-27 OND

从本质上讲,低于week的{​​{1}}值应与40配对,高于40的值应为MAM

到目前为止,我有这个:

OND

但它很笨重,并没有产生最终的回应。

谢谢。

1 个答案:

答案 0 :(得分:1)

使用numpy.where

condition = df.week < 40
df['season'] = np.where(condition, 'MAM', 'OND')
print (df)
     Name  year  week        date season
0    Adam  2016    16  2016-04-24    MAM
1    Mary  2016    17  2016-05-01    MAM
2    Jane  2016    20  2016-05-22    MAM
3     Joe  2016    17  2016-05-01    MAM
4  Arthur  2017    44  2017-11-05    OND
5     Liz  2017    41  2017-10-15    OND
6  Janice  2016    47  2016-11-27    OND

编辑:

要将string转换为integer,请使用astype

condition = df.week.astype(int) < 40

或转换列:

df.week = df.week.astype(int)
condition = df.week < 40