【问题标题】:One-line solution for Pandas dataframe searchPandas 数据框搜索的一站式解决方案
【发布时间】:2020-01-17 16:13:14
【问题描述】:

我想知道是否有一个(或两个!)解决方案,而不是使用多个 for 循环来解决以下问题:

如果 $ID$orient$direct 相同,我想计算任何 $weight 值之间的差异:

$ID $spec   $view   $orient $direct $weight
9247    1   post    stance      0       2038.66 
9247    2   post    stance      15b     2177.74 
9247    4   post    stance      15f     1559.62 
9247    5   ant     stance      15b     2271.89     
9247    6   ant     stance      0       2075.44     
9247    7   ant     stance      15f     1438.31     
9247    8   post    fall        15a     1665.60     
9247    9   post    fall        15p     1742.82     
9119    1   ant     fall        0       994.48      
9119    2   ant     fall        15b     1081.44     
9119    3   post    fall        15b     1024.18 
9119    4   post    fall        0       1093.46 
9119    5   post    stance      15a     1220.13     
9119    6   post    stance      15p     1089.72     
9119    7   post    fall        15f     1056.21     

比如要计算第一行和第五行的差值(2038.66 - 2075.44 = −36.78)等等,写在这样一个新的dataframe中:

$ID $orient $direct $weight-difference
9247    stance      0       −36.78  
9247    stance      15b     −94.15

谢谢!

【问题讨论】:

  • 到目前为止你有什么尝试?
  • 你想用单线创建所有对吗?
  • 类似:df.assign(difference=df.groupby(['$ID','$orient','$direct'])['$weight'].diff().mul(-1)).dropna()?
  • 我一直在测试 df.groupby(['$ID', '$orient', '$direct'], as_index=False)...
  • @anky_91,在回答部分写下你的解决方案,它会比评论更有帮助。

标签: python pandas dataframe data-science


【解决方案1】:

series.diff 与 groupby 一起使用:

df.assign(difference=df.groupby(['$ID','$orient','$direct'])['$weight'].diff().mul(-1))
                                                                      .dropna()

     $ID  $spec $view $orient $direct  $weight  difference
3   9247      5   ant  stance     15b  2271.89      -94.15
4   9247      6   ant  stance       0  2075.44      -36.78
5   9247      7   ant  stance     15f  1438.31      121.31
10  9119      3  post    fall     15b  1024.18       57.26
11  9119      4  post    fall       0  1093.46      -98.98

【讨论】:

  • 请问如何将每对的两个值写在不同的列中(而不是计算它们的差异)?一列是 $view==ant 的值,另一列是 $view==post
猜你喜欢
  • 1970-01-01
  • 2012-05-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-18
相关资源
最近更新 更多