我想向Pandas DataFrame添加额外的行。然而,对于float64
类型的列,我需要计算之前的3个观测滚动平均值,而不是简单地重复。在下面的DataFrame中,Score1
列的类型为float64
。
对于month
列,我需要增加+1。
import pandas as pd
df = pd.DataFrame({
'Month' : [1,2,3],
'Year' : [2021,2021,2021],
'Label' : ['A','A','A'],
'Score1' : [1.1,1.2,1.3]
})
如何将滚动平均值计算与复制行结合起来?预期输出:
Month Year Label Score1
1 2021 A 1.1
2 2021 A 1.2
3 2021 A 1.3
4 2021 A 1.2
5 2021 A 1.2
6 2021 A 1.2
如果我正确理解了您的问题,我提出以下解决方案:
import pandas as pd
df = pd.DataFrame({
'Month' : [1,2,3,4],
'Year' : [2021,2021,2021,2021],
'Label' : ['A','A','A','A'],
'Score1' : [1.1,1.2,1.3,1.4]
})
columns = df.dtypes
length = df.shape[0]
# copy last row in new row
df.loc[length] = df.loc[length-1]
for i in range(len(columns.index)):
if columns.iloc[i] == 'float64':
# moving average of the last 3 data
df.loc[length, columns.index[i]] = df.loc[length-3:length-1, columns.index[i]].mean()
if columns.index[i] == 'Month':
df.loc[length, columns.index[i]] = df.loc[length-1, columns.index[i]] + 1
如果最后一行是float64
类型的值,那么您要做的就是复制最后一行并替换值