列的Concat值取决于特定条件

时间:2015-12-10 17:34:58

标签: python python-2.7 python-3.x pandas dataframe

我有以下数据框:

# EPISODE PROGRAM  TITLE IS_EPIS  IS_MOVIE IS_SHOW    
1 E_N1    P_N1      T1      1        0         0
2 E_N2    P_N2      T2      0        0         1
3 E_N3    P_N3      T3      0        1         0

我正在努力获得新专栏:

# EPISODE PROGRAM  TITLE IS_EPIS  IS_MOVIE IS_SHOW  TITLE  EPISODE_TITLE
1 E_N1    P_N1       T1     1        0         0      NA        E_N1
2 E_N2    P_N2       T2     0        0         1      T2         NA        
3 E_N3    P_N3       T3     0        1         0      P_N3       NA

通过:

df['episode_title'] = df[(df.IS_EPIS == 1)].episode #GOOD

df['title'] = df[(df.IS_MOVIE == 1)].program | df[(df.IS_SHOW == 1)].title #FAIL

1 个答案:

答案 0 :(得分:2)

您可以使用loc

df.loc[df.IS_MOVIE == 1 ,'title'] = df.PROGRAM
df.loc[df.IS_SHOW == 1, 'title'] = df.TITLE
df.loc[df.IS_EPIS == 1, 'episode_title'] = df.EPISODE
print df
  EPISODE PROGRAM TITLE  IS_EPIS  IS_MOVIE  IS_SHOW title episode_title
#                                                                      
1    E_N1    P_N1    T1        1         0        0   NaN          E_N1
2    E_N2    P_N2    T2        0         0        1    T2           NaN
3    E_N3    P_N3    T3        0         1        0  P_N3           NaN