Pandas - 在多个数据帧之间编写更改日志

时间:2018-01-05 17:48:13

标签: python-3.x pandas numpy logging

我正在考虑为大型数据帧编写更改日志的最有效方法。我有数千个拥有100万行和20列的数据帧,因此效率至关重要。我有几个解决方案来检查两个数据帧之间的差异,但我无法找出记录更改的最佳方法。骨架算法是:

  1. 将df1和df2加载到内存中。
  2. 将df3初始化为df1 - 这是基线(数据库的第一个日期)
  3. 使用df1.ne(df2)
  4. 比较df1和df2
  5. 写入更改为df3的单元格(某种合并......合并和lamda ops?和df重组?)
  6. 设置df1 = df2
  7. 循环到下一个文件并加载新的df2进行比较
  8. 循环结束
  9. 将df3写入新文件(xlsx,csv等)
  10. 我相信我坚持第3步和第4步。我想我需要将屏蔽数据帧合并到df3数据帧,然后进行某种操作来连接字符串。有人有什么想法吗?

    我在循环内部尝试了以下更改df1和df2,但获得了错误的结果:

    import pandas as pd
    import numpy as np    
    df1=pd.DataFrame({'Col1' : ['blue', 2, 3, 4], 'Col2' : [90, 99, 3, 97], 'Col3' : [11, 12, 13, 14]})
    df2=pd.DataFrame({'Col1' : ['blue', 2, 6], 'Col2' : [90, 99, 99], 'Col3' : [11, 12, 13]})
    df3=df1
    mask=df2.ne(df1)
    #This is where trouble begins...df3 is overwritten so the log is only for this one comparison...
    #How do I merge the data into df3 so that df3 has the string from df3 and the additions from df2.ne(df1)
    df3=(df3.astype(str)[mask] + ' changed to: ' + df2.astype(str)[mask]).fillna(df2.astype(str)).fillna('Removed')
    

    谢谢!

0 个答案:

没有答案