将一个数据帧中的零替换为另一个数据帧中的值

时间:2017-08-15 21:06:08

标签: python pandas

我有两个数据帧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

我想用df1中的相应条目替换df2中的所有零。换句话说,如果df2中某个索引处的元素为零,那么我希望这个元素被df1中的相应条目替换。

因此,我希望df2看起来像:

   age
0    42
1    52
2    1
3    24
4    73

我尝试使用替换方法,但它无法正常工作。请帮忙 :) 提前谢谢。

3 个答案:

答案 0 :(得分:7)

您可以使用where

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

上面,df2 != 0是一个布尔数据框架。

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为True,则使用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'], Pandas执行自动索引标签对齐。 (注意上面的索引标签是0,1,3,4 - 跳过2)。因此,df2.loc[df2['age'] == 0, 'age']中的值将替换为d1['age']中的相应值。即使d1['age']是包含索引标记01234的系列,2被忽略,因为左侧没有相应的索引标签。

换句话说,

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

也可以,但右侧增加的限制是不必要的。

答案 1 :(得分: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

答案 2 :(得分:1)

或尝试mul

df1.mul(np.where(df2==1,0,1)).replace({0:1})
相关问题