Pandas Merge():从合并列追加数据并替换空值(来自问题 https://stackoverflow 的扩展。com/questions/68471939)

Pandas Merge(): Appending data from merged columns and replace null values (Extension from question https://stackoverflow.com/questions/68471939)

我想合并两个 table,同时将一个 table 中一列中的空值替换为另一个 table 中同一标记列中的非空值].

下面的代码是要合并的 table 的示例:

# Table 1 (has rows with missing values)

a=['x','x','x','y','y','y']
b=['z', 'z', 'z' ,'w', 'w' ,'w' ]
c=[1 for x in a]
d=[2 for x in a]
e=[3 for x in a]
f=[4 for x in a]
g=[1,1,1,np.nan, np.nan, np.nan]

table_1=pd.DataFrame({'a':a, 'b':b, 'c':c, 'd':d, 'e':e, 'f':f, 'g':g})
table_1


    a   b   c   d   e   f   g
0   x   z   1   2   3   4   1.0
1   x   z   1   2   3   4   1.0
2   x   z   1   2   3   4   1.0
3   y   w   1   2   3   4   NaN
4   y   w   1   2   3   4   NaN
5   y   w   1   2   3   4   NaN

# Table 2 (new table to be merged to table_1, and would need to use values in column 'c' to replace values in the same column in table_1, while keeping the values in the other non-null rows)


a=['y', 'y', 'y']
b=['w', 'w', 'w']
g=[2,2,2]
table_2=pd.DataFrame({'a':a, 'b':b, 'g':g})
table_2

    a   b   g
0   y   w   2
1   y   w   2
2   y   w   2

这是我用于合并 2 table 的代码,以及我得到的输出

merged_table=pd.merge(table_1, table_2, on=['a', 'b'], how='left')
merged_table

当前输出:

    a   b   c   d   e   f   g_x g_y
0   x   z   1   2   3   4   1.0 NaN
1   x   z   1   2   3   4   1.0 NaN
2   x   z   1   2   3   4   1.0 NaN
3   y   w   1   2   3   4   NaN 2.0
4   y   w   1   2   3   4   NaN 2.0
5   y   w   1   2   3   4   NaN 2.0
6   y   w   1   2   3   4   NaN 2.0
7   y   w   1   2   3   4   NaN 2.0
8   y   w   1   2   3   4   NaN 2.0
9   y   w   1   2   3   4   NaN 2.0
10  y   w   1   2   3   4   NaN 2.0
11  y   w   1   2   3   4   NaN 2.0

期望的输出:

    a   b   c   d   e   f   g
0   x   z   1   2   3   4   1.0
1   x   z   1   2   3   4   1.0
2   x   z   1   2   3   4   1.0
3   y   w   1   2   3   4   2.0
4   y   w   1   2   3   4   2.0
5   y   w   1   2   3   4   2.0

有一些问题需要您解决:

  • 表1,2 'g'列类型:应该是float。所以我们对 tables 1,2;

    都使用 DataFrame.astype({'column_name':'type'})
  • Indexes. 您可以按索引插入数据,因为 table_1 的其他列包含相同的数据:'y w 1 2 3 4' .因此,我们应该从 table 1 的 'g' 列过滤 NaN 值:ind=table_1[*pd.isnull*(table_1['g'])] 并使用来自 table 1 的新索引创建一个新系列,该新索引涵盖 [=37] 的 NaN 值=]: pd.Series(table_2['g'].to_list(),index=ind.index)

试试这个解决方案:

  table_1=table_1.astype({'a':'str','b':'str','g':'float'})
  table_2=table_2.astype({'a':'str','b':'str','g':'float'})
  ind=table_1[pd.isnull(table_1['g'])]
  table_1.loc[ind.index,'g']=pd.Series(table_2['g'].to_list(),index=ind.index) 

这是输出。