根据另一个数据框的索引和列填充数据框

时间:2020-01-28 20:28:16

标签: python python-3.x pandas dataframe

我想知道是否可以用预定索引填充空数据框,并用另一个数据框填充列?在这里,我有2个数据帧df1和df2,我想用df1中的值填充df2,但要保持df2的形状。列的顺序也不相同。

values1 = pd.Series(['P1','P2','P3','P4','P5'])
values2 = pd.Series([30,40,50,70,80])
values3 = pd.Series([10,20,30,40,50])
df1 = pd.DataFrame({'A':values1,'C':values2,'B':values3})
df1 = df1.set_index(['A'])

df2 = pd.DataFrame(columns = ['A','B','C','D'])
df2_a_val = pd.Series(['P1','P2','P3','P4','P5','P6','P7','P8'])
df2['A'] = df2_a_val
df2 = df2.set_index(['A'])

1 个答案:

答案 0 :(得分:0)

这是使用merge的一种方式:

df2 = (df2
      .merge(df1, left_index=True, right_index=True, how='left', suffixes=('','_'))
      .drop(['B','C'], 1)
      .rename(columns={'C_': 'C', 'B_': 'D'}))

      D     C     D
A                  
P1  NaN  30.0  10.0
P2  NaN  40.0  20.0
P3  NaN  50.0  30.0
P4  NaN  70.0  40.0
P5  NaN  80.0  50.0
P6  NaN   NaN   NaN
P7  NaN   NaN   NaN
P8  NaN   NaN   NaN