如何将值从数据框添加到另一个数据框以获取正确的索引?

时间:2020-03-16 14:19:20

标签: python pandas

我想向df_trials添加一列“方向”,其中x> 0,y = 0的值为7,x = 0,y> 0的值为8。 我分别为每个方向提供了数据框。

df_trials_direction_7 = df_trials_clean[df_trials_clean["target_x"] > 0]
df_trials_direction_7 = df_trials_direction_7[df_trials_direction_7["target_y"] == 0]
df_trials_direction_7['direction']=7

df_trials_direction_8 = df_trials_clean[df_trials_clean["target_x"] == 0]
df_trials_direction_8 = df_trials_direction_8[df_trials_direction_8["target_y"] > 0]
df_trials_direction_8['direction']=8

df_trials_clean看起来像这样:

user trial target_x target_y
1    2     10       0
     3     0        5
2    1     4        0
     4     0        6

我尝试过:

df_trials_clean['direction']=df_trials_direction_8['direction']
df_trials_clean['direction']=df_trials_direction_7['direction']

但是这只会在该列中添加7,并将NaN放置在应为8的位置。 我将其简化了一点,总共有8个方向,因此简单地将NaN替换为8就是行不通的。

所需的输出是:

user trial target_x target_y direction
1    2     10       0        7
     3     0        5        8
2    1     4        0        7
     4     0        6        8

1 个答案:

答案 0 :(得分:0)

您可以使用布尔条件和np.select,这样,如果一行不满足任何条件,则将分配0。

cond1 = (df['target_x'] >  0) & (df['target_y'] == 0)
cond2 = (df['target_x'] == 0) & (df['target_y'] >  0)

df['direction'] = np.select([cond1, cond2], [7, 8])
df

输出:

            target_x  target_y  direction
user trial                               
1    2            10         0          7
     3             0         5          8
2    1             4         0          7
     4             0         6          8