【问题标题】:Python - Extend data frame by differences for numeric columns with split by unique IDsPython - 通过唯一ID拆分的数字列的差异扩展数据框
【发布时间】:2019-04-10 12:24:28
【问题描述】:

我想参考 ID 将计算出的差异添加到现有数据框。差异被保存到单独的数据框中。

实际dataFrame有如下视图df1

 Id   Col1   Col2  Col3
 567   6       7    9
 567   8       10   18 
 567   9       11   20  
 567   10      12   30   
 567   4       16   57
 ...   ...     ...  ...
 1568   6       7     9
 1568   8       10   18 
 1568   9       11   20  
 1568   10      12   30   
 1568   4       16   57

为每个 Id 分别保存到 df2 的计算差异,例如 Id=567

 Col1_d1  Col2_d1   Col3_d1
  NaN       NaN       NaN
  -2        -3        -9 
  -1        -1        -2  
  -1        -1        -10   
   6        -4        -27

另外,NaNvalues 我由0 填写。

我尝试使用groupbymap,但没有成功。

L1 = [x for _, x in df1.groupby(df1['Id'])]

鉴于Id 所需的分组,我如何将它与我的第二个数据帧df2 合并?

我尝试通过:list(map(lambda x: df1.append(x), L1))

预期结果:

 Id   Col1   Col2  Col3  Col1_d1  Col2_d1   Col3_d1
 567   6       7    9      0          0        0
       8       10   18     -2        -3        -9 
       9       11   20     -1        -1        -2 
       10      12   30     -1        -1        -10    
       4       16   57      6        -4        -27
 1568  6       7    9       0         0        0
       8       10   18     -2        -3        -9 
       9       11   20     -1        -1        -2 
       10      12   30     -1        -1        -10    
       4       16   57      6        -4        -27

感谢您的任何想法和帮助。谢谢!

【问题讨论】:

    标签: python list append apply pandas-groupby


    【解决方案1】:

    按用途固定:

     df1.reset_index(inlace = True)
     df2['index'] = df1['index']
     dfList = [df1, df2]
     reduce(lambda x, y: pd.merge(x, y, on = 'index'), dfList)
    

    【讨论】:

      猜你喜欢
      • 2019-09-20
      • 2019-04-04
      • 2021-05-12
      • 1970-01-01
      • 2020-10-01
      • 2023-01-28
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多