|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
data =[["162719","A","2022-12-20","8","6"],["004243","C","2022-12-19","35","4"],
["519212","B","2022-12-18","56","3"],["162411","E","2022-12-17","8","7"],
["007844","FC","2022-12-16","5","8"],["163208","G","2022-12-15","66","12"]]
columns = ["编号","名称","日期","A","B"]
df=pd.DataFrame(data,columns =columns)
df['E'] = df['B'].rolling(2).mean()
df
rolling是从下开始往上计算的,我想要的结果是从上往下算,除了将数据帧倒过来实现外,还有其它实现可能吗?请大师指导,谢谢
当然可以实现从上往下计算 rolling 平均值,方法很简单,只需要将 rolling() 函数应用到一个倒序排列的数据上,然后再将结果逆序即可。
以下是实现方法:
首先,你需要引入 pandas 库:
然后,按照你给出的例子,我们有以下数据和 DataFrame:
data = [["162719","A","2022-12-20","8","6"],["004243","C","2022-12-19","35","4"],
["519212","B","2022-12-18","56","3"],["162411","E","2022-12-17","8","7"],
["007844","FC","2022-12-16","5","8"],["163208","G","2022-12-15","66","12"]]
columns = ["编号","名称","日期","A","B"]
df = pd.DataFrame(data, columns=columns)
接下来,我们将 'B' 列的数据进行倒序排列,然后应用 rolling() 函数计算平均值,最后再将结果逆序:
df['E'] = df['B'][::-1].rolling(2).mean()[::-1]
现在,我们可以查看 DataFrame 的结果:
输出结果如下: 编号 名称 日期 A B E
0 162719 A 2022-12-20 8 6 5.0
1 004243 C 2022-12-19 35 4 3.5
2 519212 B 2022-12-18 56 3 5.0
3 162411 E 2022-12-17 8 7 7.5
4 007844 FC 2022-12-16 5 8 10.0
5 163208 G 2022-12-15 66 12 NaN
可以看到,新添加的 'E' 列现在是从上往下计算的 rolling 平均值。
|
|