如何对数据帧中两个连续位置的信息求和

时间:2016-02-03 11:51:26

标签: python pandas

我有一个pandas数据帧,其位置为k,y。例如

pos k y
123 0.7 0.5
124 0.4 0.1
125 0.3 0.2
126 0.4 0.1
128 0.3 0.6
130 0.4 0.9
131 0.3 0.2

我想在k和y中总结信息

123 1.1 0.6
125 0.7 0.3
128 0.3 0.6
130 0.7 1.1

所以输出只有第一个位置和值的总和,第一个位置和它后面的直接连续数字。

我尝试过pandas分组

for k,g in df.groupby(df['pos'] - np.arange(df.shape[0])):
   u=g.ix[0:,2:].sum()

但它的所有连续数字都是我不想要的

我需要快速,因为我的数据文件中有2611774行

3 个答案:

答案 0 :(得分:0)

希望这能解决您的问题

import pandas as pd
df = pd.DataFrame( columns=['pos','k','y'])
cf = pd.DataFrame( columns=['pos','k','y'])
df['pos']=123, 124,125,126,128,130,131
df['k']=.7,.4,.3,.4,.3,.4,.3
df['y']=.5,.1,.2,.1,.6,.9,.2
row=0
while 1:
    if row+1<len(df):
        if(df.loc[row]['pos']+1==df.loc[row+1]['pos']):
            cf.loc[row]= df.loc[row]+df.loc[row+1]
            cf.loc[row]['pos']=df.loc[row]['pos']
            row=row+2
        else:
            cf.loc[row]= df.loc[row]
            row=row+1
    else:
        break
print cf

答案 1 :(得分:0)

之前我没有使用过pandas,但是如果你有机会将数据用作列表,那么这应该可行。

def SumNext(L):
  N = xrange(len(L)-1)
  Output = [L[i]+L[i+1] for i in N]
  return Output

如果输入列表,此函数将为您提供连续元素的总和。

A = [1,1,2,3,5,8,13] SumNext(A)=&gt; [2,3,5,8,13]

然后你只需要将值读出到你喜欢的地方,当你获得大量元素时,在列表中做事情(而不是while循环)要快得多。

然后您只需要弄清楚将输出传递回数据框的实现。

答案 2 :(得分:0)

也许这比一个循环更快,但它不会对我认为你期望的位置123和124然后130和131求和,因为它将连续的奇数位置与129和130,131和132相加。 。

df = df.set_index('pos')
df_odd = df.loc[df.index.values % 2 == 1]
df_even = df.loc[df.index.values % 2 == 0]
df_even = df_even.set_index(df_even.index.values - 1)
df_odd.add(df_even, fill_value = 0)

结果:

pos k   y
123 1.1 0.6
125 0.7 0.3
127 0.3 0.6
129 0.4 0.9
131 0.3 0.2