我有一个包含11列的数据框:Status1-Status5,Time1-Time5& Time_Min
df = pd.DataFrame([[100,200,150,400,500,'a','b','a','c','a',100], [300,400,200,500,250,'b','b','c','c','c',200]], columns=['TIME_1', 'TIME_2', 'TIME_3', 'TIME_4', 'TIME_5','STATUS_1','STATUS_2','STATUS_3','STATUS_4','STATUS_5','TIME_MIN'])
我想重现我目前在SAS中执行以下操作的代码
IF TIME_1 = TIME_MIN THEN STATUS = STATUS_1;
ELSE IF TIME_2 = TIME_MIN THEN STATUS = STATUS_2;
ELSE IF TIME_3 = TIME_MIN THEN STATUS = STATUS_3;
ELSE IF TIME_4 = TIME_MIN THEN STATUS = STATUS_4;
ELSE STATUS = STATUS_5;
列STATUS的预期输出为
['a','c']
我尝试沿着这些线构建一些东西(需要用ifs扩展)
df['STATUS'] = [a if x == y else b for x,y,a,b in df[['TIME_MIN','TIME_1','STATUS_1','STATUS_2']]]
但这只是一个错误。我确定这是一个简单的修复,但我无法弄明白。
答案 0 :(得分:6)
你可以写一个函数
def get_status(df):
if df['TIME_1'] == df['TIME_MIN']:
return df['STATUS_1']
elif df['TIME_2'] == df['TIME_MIN']:
return df['STATUS_2']
elif df['TIME_3'] == df['TIME_MIN']:
return df['STATUS_3']
elif df['TIME_4'] == df['TIME_MIN']:
return df['STATUS_4']
else:
return df['STATUS_5']
df['STATUS'] = df.apply(get_status, axis = 1)
或者使用非常嵌套的np.where,
df['STATUS'] = np.where(df['TIME_1'] == df['TIME_MIN'], df['STATUS_1'],\
np.where(df['TIME_2'] == df['TIME_MIN'], df['STATUS_2'],\
np.where(df['TIME_3'] == df['TIME_MIN'], df['STATUS_3'],\
np.where(df['TIME_4'] == df['TIME_MIN'], df['STATUS_4'], df['STATUS_5']))))
答案 1 :(得分:2)
不是很漂亮但你可以使用.eq
method进行平等广播。
m = df.iloc[:, :5].eq(df['TIME_MIN'], axis=0)
m.columns = 'STATUS_' + m.columns.str.extract('TIME_(.*)')
df['STATUS'] = df[m].bfill(axis=1).iloc[:, 0]
答案 2 :(得分:0)
您可以使用条件和选择
df = pd.DataFrame([[100,200,150,400,500,'a','b','a','c','a',100], [300,400,200,500,250,'b','b','c','c','c',200]], columns=['TIME_1', 'TIME_2', 'TIME_3', 'TIME_4', 'TIME_5','STATUS_1','STATUS_2','STATUS_3','STATUS_4','STATUS_5','TIME_MIN'])
condition= [df['TIME_1'] == df['TIME_MIN'],
df['TIME_2'] == df['TIME_MIN'],
df['TIME_3'] == df['TIME_MIN'],
df['TIME_4'] == df['TIME_MIN'],
df['TIME_4'] == df['TIME_MIN']]
choice= [df['STATUS_1'],df['STATUS_2'],df['STATUS_3'],df['STATUS_4'],df['STATUS_5']]
df['STATUS'] =np.select(condition,choice,default="")
col_required=['TIME_1','TIME_2','TIME_3','TIME_4','TIME_5','TIME_MIN','STATUS']
df=df[col_required]
df
输出
TIME_1 TIME_2 TIME_3 TIME_4 TIME_5 TIME_MIN STATUS
0 100 200 150 400 500 100 a
1 300 400 200 500 250 200 c