groupby后减法

2024-05-14 12:50:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据帧:

   Allotment    Date        NDII_Mean
   Arnstson     19900619    0.073023
   A_Annex      19900619    0.131290
   Arnstson     19900620    0.045553
   A_Annex      19900620    0.688850

我想按Allotment分组,然后用19900619日期减去{}日期。在

我希望我的输出看起来像这样:

^{pr2}$

Tags: 数据datemeanannexpr2arnstsonallotmentndii
2条回答

您可以使用reshape strategies (^{}),这样就可以自然地减去结果。在

df = pd.DataFrame([['Arnstson' ,   19900619 ,  0.073023],
                   ['A_Annex'  ,   19900619 ,  0.131290],
                   ['Arnstson' ,   19900620 ,  0.045553],
                   ['A_Annex'  ,   19900620 ,  0.688850]],
                 columns=['Allotment', 'Date', 'NDII_Mean'])
dfreshape = df.pivot('Allotment', 'Date')    
#           NDII_Mean          
# Date       19900619  19900620
# Allotment                    
# A_Annex    0.131290  0.688850
# Arnstson   0.073023  0.045553    

然后,您可以简单地使用索引/切片来获得所需的结果:

^{pr2}$

完整代码:

dfreshape = df.pivot('Allotment', 'Date')   
dfreshape['NDII_Mean',19900620] - dfreshape['NDII_Mean',19900619]
difference = lambda x: ['x['Allotment'][0], x.ix[1]['NDII_Mean'] - x.ix[0]['NDII_Mean']]
df_diffs = DataFrame([difference(x[1].reset_index(drop = True)) for x in df.groupby(['Allotment'])])
df_diffs.columns = ['Allotment', 'NDII_Mean']
print df_diffs

  Allotment  NDII_Mean
0   A_Annex    0.55756
1  Arnstson   -0.02747

相关问题 更多 >

    热门问题