2017-08-16 167 views
1

有兩個數據幀具有相同的列,索引和列的順序相同。我稱他們爲tableA和tableB。基於其他數據幀替換值

tableA = pd.DataFrame({'col1':[np.NaN,1,2],'col2':[2,3,np.NaN]}) 
    tableB = pd.DataFrame({'col1':[2,4,2],'col2':[2,3,5]}) 

    tableA       tableB 
       col1 col2     col1 col2 
      0  na  2    0  2  2 
      1  1  3    1  4  5 
      2  2  na    2  2  5 

我想將tableB的某些值替換爲'NA',其中tableA的相同位置的值爲na。 現在,我使用循環逐列地做。

for n in range(tableB.shape[1]): 
     tableB.iloc[:,n] = tableB.iloc[:,n].where(pd.isnull(tableA.iloc[:,n])==False,'NA') 

    tableB       
       col1 col2    
      0  NA  2    
      1  4  5    
      2  2  NA    

有沒有其他方法可以不使用循環?我曾嘗試使用替換,但它只能更改第一列。

tableB.replace(pd.isnull(tableA), 'NA', inplace=True) #only adjust the first column. 

感謝您的幫助!

回答

0

我想你需要wherenumpy.where

df = tableB.where(tableA.notnull()) 
print (df) 
    col1 col2 
0 NaN 2.0 
1 4.0 3.0 
2 2.0 NaN 

2.

df = pd.DataFrame(np.where(tableA.notnull(), tableB, np.nan), 
        columns=tableB.columns, 
        index=tableB.index) 
print (df) 
    col1 col2 
0 NaN 2.0 
1 4.0 3.0 
2 2.0 NaN 
+0

Can can be filtered out by notnull? –

+0

是的,確切地說。但是,如果有字符串「NA」需要首先'df = df.replace('NA',np.nan)' – jezrael

+0

感謝您的幫助! –

0

你可以使用mask

In [7]: tableB.mask(tableA.isnull()) 
Out[7]: 
    col1 col2 
0 NaN 2.0 
1 4.0 3.0 
2 2.0 NaN 
0
tableB[tableA.isnull()] = np.nan