Python 熊猫在奇数行上取平均值

Python 熊猫在奇数行上取平均值,python,pandas,dataframe,Python,Pandas,Dataframe,我想用当前行和下一行(其中列为数字)的平均值填充数据框中每行之间的数据 起始数据: time value value_1 value-2 0 0 0 4 3 1 2 1 6 6 中间df: time value value_1 value-2 0 0 0 4 3 1 1 0 4 3 #duplicate of row 0 2 2

我想用当前行和下一行(其中列为数字)的平均值填充数据框中每行之间的数据

起始数据:

   time value value_1  value-2
0   0    0      4        3
1   2    1      6        6
中间df:

   time value value_1  value-2
0   0    0      4        3
1   1    0      4        3     #duplicate of row 0
2   2    1      6        6
3   3    1      6        6     #duplicate of row 2
我想创建df_1:

   time value value_1  value-2
0   0    0      4        3
1   1    0.5    5        4.5     #average of row 0 and 2
2   2    1      6        6
3   3    2      8        8       #average of row 2 and 4
为此,我附加了起始数据帧的副本,以创建如上所示的中间数据帧:

df = df_0.append(df_0)
df.sort_values(['time'], ascending=[True], inplace=True)
df = df.reset_index()
df['value_shift'] = df['value'].shift(-1)
df['value_shift_1'] = df['value_1'].shift(-1)
df['value_shift_2'] = df['value_2'].shift(-1)
然后我想对每一列应用一个函数:

def average_vals(numeric_val):
    #average every odd row
    if int(row.name) % 2 != 0:
        #take average of value and value_shift for each value
        #but this way I need to create 3 separate functions

有没有一种方法可以做到这一点,而不必为每一列编写单独的函数并逐个应用于每一列(在实际数据中,我有几十列)?

这个方法如何使用and

解释 重新索引,分半步
Reindex(np.arange(len(df.index)*2)/2)

这将产生如下数据帧:

     time  value  value_1  value-2
0.0   0.0    0.0      4.0      3.0
0.5   NaN    NaN      NaN      NaN
1.0   2.0    1.0      6.0      6.0
1.5   NaN    NaN      NaN      NaN
然后使用
DataFrame.interpolate
填充
NaN
值。。。。默认值为线性插值,因此在本例中为平均值

最后,使用
.reset\u index(drop=True)
修复索引

应该给

   time  value  value_1  value-2
0   0.0    0.0      4.0      3.0
1   1.0    0.5      5.0      4.5
2   2.0    1.0      6.0      6.0
3   2.0    1.0      6.0      6.0
   time  value  value_1  value-2
0   0.0    0.0      4.0      3.0
1   1.0    0.5      5.0      4.5
2   2.0    1.0      6.0      6.0
3   2.0    1.0      6.0      6.0