【问题标题】:How to calculated the difference between levels values based in clusterization result?如何根据聚类结果计算级别值之间的差异?
【发布时间】:2020-04-10 12:40:10
【问题描述】:

假设我们有一个包含两列的 pandas 数据框:

Col1  Col2         
  0    15         
  0    20         
  0    30         
  1    40         
  1    45         
  0    50     
  0    55         
  2    60         
  2    70

我需要根据 col2 在其他数据框或数组中计算:

Col1  Col2     
 0     30-15=15    
 1     45-40=5     
 0     55-50=5     
 2     70-60=10

终于出结果了:

Col1  Col2     
  0    15    
  1    5     
  0    5     
  2    10

谢谢

【问题讨论】:

  • 你能解释一下那个计算的算法是什么吗?
  • 第 1 列中的每个标签确定一个层(第 2 列是深度)所以我需要知道每层的厚度。

标签: python pandas numpy


【解决方案1】:

使用np.ptp(峰到峰)

df.groupby(df.Col1.ne(df.Col1.shift()).cumsum()).Col2.apply(np.ptp)

Col1  Col2     
  0    15    
  1    5     
  0    5     
  2    10

【讨论】:

  • @EdwinMald 你也可以df.groupby([df.Col1.ne(df.Col1.shift()).cumsum(), 'Col1']).Col2.apply(np.ptp)。它对你有用吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多