你可以使用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
,3
和4
的系列,但由於在左側沒有相應的索引標籤,所以2
被忽略。
換句話說,
df2.loc[df2['age'] == 0, 'age'] = df1.loc[df2['age'] == 0, 'age']
將工作爲好,但在右手側所添加的限制是不必要的。
謝謝。但是,當我嘗試df2.where(df2 ['age']!= 0,df1)我得到AttributeError:'浮動'對象沒有屬性'全' – ZeusofCode
我認爲你遇到[此錯誤](https:// stackoverflow.com/q/26973803/190597) - 你可以通過升級你的熊貓版本來修復它。 – unutbu
熊貓版本無法更改,因爲它安裝在服務器上,我只能使用那個:(我的熊貓版本是0.15.1' – ZeusofCode