根据第二个更新数据框中的行

时间:2019-08-29 08:25:08

标签: python pandas dataframe

我有以下数据框df1:

                          AS  AT  CH  TR 
James Robert/01/08/2019   0   0   0   1 
James Robert/18/08/2019   0   0   0   1 
John Smith/01/08/2019     1   0   0   0 
John Smith/02/08/2019     0   1   0   0 

和df2:

                               TIME
Andrew Johnson/08/08/2019      1
James Robert/01/08/2019        0.5
John Smith/02/08/2019          1

如果两个数据帧中都存在索引值(示例:James Robert/01/08/2019John Smith/02/08/2019),那么我想删除df1中的行(如果df1["Column with a value"] - df2['TIME'] = 0的值,否则我想删除)更新值。

所需的输出为:

                          AS  AT  CH  TR
James Robert/01/08/2019   0   0   0   0.5
James Robert/18/08/2019   0   0   0   1
John Smith/01/08/2019     1   0   0   0

如果两个数据帧中都有一行,我可以将其从df1中删除,但是我找不到添加这种特殊条件的方法:"df1["Column with a value"]"

谢谢

1 个答案:

答案 0 :(得分:0)

与其使用索引,不如使用索引作为列。将df2['index']列放在列表中。在df1中使用isin方法将该列表用作参数。

df2['index'] = df2.index
df1['index'] = df1.index

filtered_df1 = df1[df1['index'].isin(df2['index'].values.tolist())]

使用'index'列和'Time'df2列的值创建字典,然后将其映射到filtered_df1

your_dict = dict(zip(df2['index'],df2['Time']))
filtered_df1['Subtract Value'] = filtered_df1['index'].map(your_dict).fillna(value = 0)

然后在那做减法。

final_df = filtered_df1.sub(filtered_df1['Subtract Value'], axis=0)

希望这会有所帮助。