繁体   English   中英

更改熊猫数据框中的值是另一个数据框中存在同一行

[英]Changing value in pandas dataframe is same row is present in another dataframe

我有傻瓜。 2个熊猫数据框:

df1 = pandas.DataFrame(data = {'col1' : [1, 2, 3, 4, 5], 'col2' : [10, 11, 12, 13, 14], 'col3' : [0,2,0,-1,0]}) 
df2 = pandas.DataFrame(data = {'col1' : [1, 2, 3], 'col2' : [10, 11, 12], 'col6' : [20, 31, 12]})

如果col1col2在df1和df2中具有相同的值,如何将df1中的col3中的值更改为0。 df1的结果应如下所示:

  col1  col2  col3
0     1    10     0
1     2    11     0
2     3    12     0
3     4    13    -1
4     5    14     0

如果在col1col2上合并两个DataFrame,则结果DataFrame将具有行,其中两个DataFrame在这些列中具有相同的值。 但是,大熊猫在合并时会失去索引 您可以在合并之前使用reset_index来保留索引并在.loc使用该索引:

df1.loc[df1.reset_index().merge(df2, on=['col1', 'col2'])['index'], 'col3'] = 0

df1
Out: 
   col1  col2  col3
0     1    10     0
1     2    11     0
2     3    12     0
3     4    13    -1
4     5    14     0

快速的numpy解决方案。 idf1获得每一行的索引,而从df2另一行的索引。 我使用==来确定哪些单元格相等。 all(2)确定一行中的所有单元格是否等于另一行中的所有单元格。 如果为true,则对应的一组索引表示一个匹配项。 因此, i[0][matches]告诉我df1中与i[1][matches]表示的df2中的行匹配的所有行。 但是我只需要更改df1值,所以我只使用i[0][matches]在第3列上切片df1 ,然后分配0

def pir(df1, df2):
    i = np.indices((len(df1), len(df2)))
    matches = (df2.values[i[1], :2] == df1.values[i[0], :2]).all(2)
    df = df1.copy()
    df.iloc[i[0][matches], 2] = 0
    return df

pir(df1, df2)

在此处输入图片说明


定时

def ayhan(df1, df2):
    df1 = df1.copy()
    df1.loc[df1.reset_index().merge(df2, on=['col1', 'col2'])['index'], 'col3'] = 0
    return df1

在此处输入图片说明

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM