简体   繁体   English

基于来自另一个数据帧的索引和列填充数据帧

[英]Filling dataframe based on index and column from another dataframe

I am wondering if it is possible to fill an empty dataframe with a predetermined index and columns with another dataframe?我想知道是否可以用预定的索引和列填充另一个数据帧的空数据帧? Here I have 2 dataframes df1 and df2, I want to fill df2 with values from df1, but keep the shape of the df2.这里我有 2 个数据帧 df1 和 df2,我想用 df1 中的值填充 df2,但保持 df2 的形状。 The columns will also not be the same order.列的顺序也不会相同。

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'])

Here's a way you can do using merge :这是您可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM