取两个数据帧的并集并分别添加resp列

时间:2018-05-28 07:26:36

标签: python pandas dataframe

我有两个数据帧,我需要创建这两个数据帧的联合(第一列' A')。

df1 = pd.DataFrame({'A' : ['a','b','c'], 'B' : [10,20,30], 'C' : [2,5,3]})
df2=  pd.DataFrame({'A' : ['a','b','d'], 'B' : [34,21,45], 'C' : [1,5,5]})

输出 -

   A   f_M   d_M  f_B  d_B
0  a   10     2    34   1
1  b   20     5    21   5
2  c   30     3     0   0
3  d   0      0    45   5

这是创建的新数据框,其中包含两列数据框(' A')。如果' B'列在df1和f_B中有值,则f_M列如果它在df2中则为0,如果不在任何df1 / df2中则为0。

2 个答案:

答案 0 :(得分:3)

concatset_index一起使用,以避免重复列名称add_suffix

d = {'B':'f','C':'d'}
df = (pd.concat([df1.set_index('A').rename(columns=d).add_suffix('_M'), 
                df2.set_index('A').rename(columns=d).add_suffix('_B')], axis=1)
        .fillna(0)
        )
print (df)
    f_M  d_M   f_B  d_B
a  10.0  2.0  34.0  1.0
b  20.0  5.0  21.0  5.0
c  30.0  3.0   0.0  0.0
d   0.0  0.0  45.0  5.0

对于专栏:

d = {'B':'f','C':'d'}
df = (pd.concat([df1.set_index('A').rename(columns=d).add_suffix('_M'), 
                df2.set_index('A').rename(columns=d).add_suffix('_B')], axis=1)
        .fillna(0)
        .rename_axis('A')  
        .reset_index()
        )
print (df)
   A   f_M  d_M   f_B  d_B
0  a  10.0  2.0  34.0  1.0
1  b  20.0  5.0  21.0  5.0
2  c  30.0  3.0   0.0  0.0
3  d   0.0  0.0  45.0  5.0

答案 1 :(得分:3)

这看起来像是外% A = [sin(t) 0;0 cos(t)]; B = [0.5; 0.0]; C = [1 0; 0 1]; D = [0; 0]; x0 = [-1;1]; % the initial state must have two elements as this is a second-order system u = 0; % constant zero input, but can be modified N = 1000; h = 0.01; t = (0:N-1)*h; x_vec = []; y_vec = []; xk = x0; yk = [0;0]; for k=1:N Ad = eye(2)+h*[sin(t(k)) 0; 0 cos(t(k))]; Bd = h*B; % C and D remain the same yk = C*xk + D*u; xk = Ad*xk + Bd*u; x_vec = [x_vec, xk]; % keep results in memory y_vec = [y_vec, yk]; end % Plot output response plot(t,y_vec); 的经典用例:

merge

要考虑列,请将df1.merge(df2, on='A', how='outer', suffixes=('_M', '_B')).fillna(0) A B_M C_M B_B C_B 0 a 10.0 2.0 34.0 1.0 1 b 20.0 5.0 21.0 5.0 2 c 30.0 3.0 0.0 0.0 3 d 0.0 0.0 45.0 5.0 map

一起使用
DataFrame.rename