python - Pandas 中的移位和乘法
问题描述
我有一个熊猫数据框,如下所示:
Year Ship Age Surviving UEC
2018 12.88 13 0.00 17.2
2019 12.57 12 0.02 17.2
2020 12.24 11 0.06 17.2
2021 11.95 10 0.18 17.2
2022 11.77 9 0.37 17.2
2023 11.70 8 0.60 17.2
2024 11.75 7 0.81 17.2
2025 11.93 6 0.94 17.2
2026 12.12 5 0.99 0.3
2027 12.34 4 1.00 0.3
2028 12.56 3 NaN 0.3
2029 12.76 2 NaN 0.3
2030 12.93 1 NaN 0.3
我想通过一次将所有列向下移动 1 来将 Ship、Surviving 和 UEC 列相乘,因此输出 df2 应该如下所示:
df2
Stock_uec
0 df1.iloc[:10,1]*df1.iloc[:10,3]*df1.iloc[:10,4]
1 df1.iloc[1:11,1]*df1.iloc[1:11,3]*df1.iloc[1:11,4]
3 df1.iloc[2:12,1]*df1.iloc[2:12,3]*df1.iloc[2:12,4]
下面是我的代码,但我没有得到预期的结果。
for i, row in df1.iterrows():
out=df1.iloc[i:i+10,1].shift(1,axis=0)*df1.iloc[i:i+10,3].shift(1,
axis=0)*df1.iloc[i:i+10,4].shift(1, axis=0)
print(out)
谢谢您的帮助。
解决方案
IIUC,我想你想要:
df.loc[:,'shipping_utc'] = 0
for i in range(df.shape[0]):
df.loc[i:,'shipping_utc'] = df.iloc[i:][['Ship','Surviving','UEC']].prod(axis=1) + df.loc[i:,'shipping_utc']
输出
df
Out[25]:
Year Ship Age Surviving UEC shipping_utc
0 2018 12.88 13 0.00 17.2 0.00000
1 2019 12.57 12 0.02 17.2 8.64816
2 2020 12.24 11 0.06 17.2 37.89504
3 2021 11.95 10 0.18 17.2 147.98880
4 2022 11.77 9 0.37 17.2 374.52140
5 2023 11.70 8 0.60 17.2 724.46400
6 2024 11.75 7 0.81 17.2 1145.90700
7 2025 11.93 6 0.94 17.2 1543.07392
8 2026 12.12 5 0.99 0.3 32.39676
9 2027 12.34 4 1.00 0.3 37.02000
10 2028 12.56 3 NaN 0.3 41.44800
11 2029 12.76 2 NaN 0.3 45.93600
12 2030 12.93 1 NaN 0.3 50.42700
推荐阅读
- ios - 从委派函数调用 CocoaLumberjack 时如何获取正确的 fileName 函数行
- php - 根据 Laravel 中的用户角色对同一路由使用不同的控制器
- javascript - Vue JS props 甚至在父级中声明了 undefined
- php - 在 PHP 网站中使用“通用”导航栏重定向时遇到问题
- php - 4个表插入 - mysql
- python - 60 个倾斜的圆圈,中心有一个洞
- orange - Orange中的离散类变量是什么?
- ffmpeg - 将过滤器与普通选项相结合
- java - 难以执行此打印出时间的代码
- android - 为什么自定义 ArrayAdapter 不在 ListView 中显示 TextView