1 回答
TA贡献1847条经验 获得超7个赞
可能有一种更短、更简单的方法来执行转换。但这里有一种避免循环的方法。
# create the data frame, as per the original post
data = [{'c1':10, 'c2':10},
{'c1':10,'c2':20},
{'c1':10,'c2':30},
{'c1':10,'c2':40},
{'c1':20,'c2':50},
{'c1':20,'c2':60},
{'c1':20,'c2':70}
]
df = pd.DataFrame(data) # df = Input
# 1. convert the index to an ordinary column
df = df.reset_index()
# 2. 'helper' is a column that counts 0, 1, 2, 3, ...
# and re-starts for each c1
df['helper'] = df['index'] - df.groupby('c1')['index'].transform(min)
# 3. integer division on 'helper', to get 0, 0, 1, 1, 2, 2, ...
# (identify non-overlapping pairs)
df['helper'] //= 2
# 4. now convert 'index' from ordinary column back to an Index
df = df.set_index('index')
# 5. compute the mean of c2 for value of 'c1' and each pair of observations
df = df.groupby(['c1', 'helper'])['c2'].mean()
# 6. re-order 'helper' and 'c1' to match order in output
df.index = df.index.swaplevel()
print(df)
helper c1
0 10 15
1 10 35
0 20 55
1 20 70
Name: c2, dtype: int64
添加回答
举报