【问题标题】:Changing value in pandas dataframe is same row is present in another dataframe熊猫数据框中的更改值是同一行存在于另一个数据框中
【发布时间】:2016-08-10 23:12:48
【问题描述】:

我知道了。 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

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    如果合并 col1col2 上的两个 DataFrame,则生成的 DataFrame 将包含两个 DataFrame 在这些列中具有相同值的行。但是,pandas loses the index 合并时。您可以在合并之前使用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
    

    【讨论】:

      【解决方案2】:

      一个快速的 numpy 解决方案。 i 获取来自df1 的一行和来自df2 的另一行的每个组合的索引。我使用== 来确定哪些单元格相等。 all(2) 确定一行中的所有单元格是否等于另一行中的所有单元格。如果为真,则相应的索引集表示匹配。所以,i[0][matches] 告诉我来自df1 的所有行与df2 中由i[1][matches] 表示的行匹配。但我只需要更改df1 中的值,所以我只使用i[0][matches] 对第三列的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
      

      【讨论】:

      • 感谢@piRSquared,这行是做什么的:`matches = (df2.values[i[1], :2] == df1.values[i[0], :2])。全部(2)`
      • 对于非常小的数据帧来说很快。对于较大的(> 1e5 行)可能不切实际,因为它实际上是笛卡尔积。即使对于中等大小的帧,merge 也应该表现更好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多