如何使用python Pandas减去行?

时间:2014-12-03 13:40:35

标签: python pandas

我有一个如下所示的数据框:

        C/A  UNIT       SCP     DATEn     TIMEn    DESCn  ENTRIESn    EXITSn  
0     A002  R051  02-00-00  05-01-11  00:00:00  REGULAR   3144312   1088151 
1     A002  R051  02-00-00  05-01-11  04:00:00  REGULAR   3144335   1088159 
2     A002  R051  02-00-00  05-01-11  08:00:00  REGULAR   3144353   1088177 
3     A002  R051  02-00-00  05-01-11  12:00:00  REGULAR   3144424   1088231   
4     A002  R051  02-00-00  05-01-11  16:00:00  REGULAR   3144594   1088275  
5     A002  R051  02-00-00  05-01-11  20:00:00  REGULAR   3144808   1088317   
6     A002  R051  02-00-00  05-02-11  00:00:00  REGULAR   3144895   1088328

我需要创建一个新行(ENTRIESn_hourly),该行将从前一行中减去ENTRIESn列中的每一行。有人可以帮忙吗? 干杯!

达尼

2 个答案:

答案 0 :(得分:1)

只需致电diff

In [26]:

df['Entries diff']= df['ENTRIESn'].diff()
df
Out[26]:
        C/A  UNIT       SCP     DATEn     TIMEn    DESCn  ENTRIESn   EXITSn  \
index                                                                         
0      A002  R051  02-00-00  05-01-11  00:00:00  REGULAR   3144312  1088151   
1      A002  R051  02-00-00  05-01-11  04:00:00  REGULAR   3144335  1088159   
2      A002  R051  02-00-00  05-01-11  08:00:00  REGULAR   3144353  1088177   
3      A002  R051  02-00-00  05-01-11  12:00:00  REGULAR   3144424  1088231   
4      A002  R051  02-00-00  05-01-11  16:00:00  REGULAR   3144594  1088275   
5      A002  R051  02-00-00  05-01-11  20:00:00  REGULAR   3144808  1088317   
6      A002  R051  02-00-00  05-02-11  00:00:00  REGULAR   3144895  1088328   

       Entries diff  
index                
0               NaN  
1                23  
2                18  
3                71  
4               170  
5               214  
6                87 

答案 1 :(得分:0)

你也可以先把行换一行来做到这一点:

df["ENTRIESn_hourly"] = df["ENTRIESn"] - df["ENTRIESn"].shift()

请参阅pandas.DataFrame.shift