2017-08-15 172 views
1

我有兩個dataframes DF1和DF2與值替換一個數據幀零: DF1如下所示:從另一個數據幀

age 
0 42 
1 52 
2 36 
3 24 
4 73 

DF2如下所示:

age 
0 0 
1 0 
2 1 
3 0 
4 0 

我想更換df2中的所有零與df1中的相應條目。用更多的技術術語來說,如果df2中某個索引處的元素爲零,那麼我希望該元素被df1中的相應條目替換。

因此,我想DF2的樣子:

age 
0 42 
1 52 
2 1 
3 24 
4 73 

我嘗試使用替代方法,但它不能正常工作。請幫助:) 提前致謝。

回答

6

你可以使用where

In [19]: df2.where(df2 != 0, df1) 
Out[19]: 
    age 
0 42 
1 52 
2 1 
3 24 
4 73 

以上,df2 != 0我是一個布爾型DataFrame。

In [16]: df2 != 0 
Out[16]: 
    age 
0 False 
1 False 
2 True 
3 False 
4 False 

df2.where(df2 != 0, df1)返回一個新的DataFrame。其中df2 != 0爲真,則使用相應的值df2。如果是False,則使用相應的值df1


另一種方法是,以與df.loc賦值:

df2.loc[df2['age'] == 0, 'age'] = df1['age'] 

df.loc[mask, col]選擇的df其中布爾系列,mask爲True的行,以及其中列標籤是col

In [17]: df2.loc[df2['age'] == 0, 'age'] 
Out[17]: 
0 0 
1 0 
3 0 
4 0 
Name: age, dtype: int64 

當在分配使用,例如df2.loc[df2['age'] == 0, 'age'] = df1['age'], 熊貓執行自動索引標籤對齊。 (注意上面的索引標籤是0,1,3,4 - 跳過2)。因此df2.loc[df2['age'] == 0, 'age']中的值將被替換爲d1['age']中的相應值。儘管d1['age']是索引標籤0,1,2,34的系列,但由於在左側沒有相應的索引標籤,所以2被忽略。

換句話說,

df2.loc[df2['age'] == 0, 'age'] = df1.loc[df2['age'] == 0, 'age'] 

將工作爲好,但在右手側所添加的限制是不必要的。

+0

謝謝。但是,當我嘗試df2.where(df2 ['age']!= 0,df1)我得到AttributeError:'浮動'對象沒有屬性'全' – ZeusofCode

+0

我認爲你遇到[此錯誤](https:// stackoverflow.com/q/26973803/190597) - 你可以通過升級你的熊貓版本來修復它。 – unutbu

+0

熊貓版本無法更改,因爲它安裝在服務器上,我只能使用那個:(我的熊貓版本是0.15.1' – ZeusofCode

2
In [30]: df2.mask(df2==0).combine_first(df1) 
Out[30]: 
    age 
0 42.0 
1 52.0 
2 1.0 
3 24.0 
4 73.0 

或 「否定」 beautiful @unutbu's solution

In [46]: df2.mask(df2==0, df1) 
Out[46]: 
    age 
0 42 
1 52 
2 1 
3 24 
4 73 
+1

即使df2.mask(df2 == 0,df1)的作品:) – Vaishali

+1

@Vaishali,是的,謝謝!這是美麗的unutbu解決方案的「否定」:) – MaxU

1

或者嘗試mul

df1.mul(np.where(df2==1,0,1)).replace({0:1}) 
相關問題