python - 如何在python中获取与同一项目相关但在不同日期的行并使用第一个和最后一个日期的值创建列?
问题描述
我有这张桌子:
股票代码 | 日期 | 价格 |
---|---|---|
苹果 | 2020-04-01 | 10 |
微软 | 2020-04-01 | 20 |
微软 | 2021-01-01 | 10 |
苹果 | 2021-01-01 | 5 |
苹果 | 2021-04-01 | 30 |
微软 | 2021-04-01 | 50 |
我想转变为:
股票代码 | Price_of_the_first_observation | Price_of_the_second_observation |
---|---|---|
苹果 | 10 | 30 |
微软 | 20 | 50 |
解决方案
如果您的数据已经按日期排序:
df.groupby('Ticker')['Price'].agg(Price_of_the_first_observation='first',
Price_of_the_last_observation='last')
或者,如果第二列的名称应该是Price_of_the_last_observation
:
(df.groupby('Ticker')['Price']
.agg(['first', 'last'])
.add_prefix('Price_of_the_')
.add_suffix('_observation')
)
输出:
Price_of_the_first_observation Price_of_the_last_observation
Ticker
Apple 10 30
MSFT 20 50
要对您的值进行排序:
df = df.sort_values(by='Date')
编辑:对于所有值:
(df.assign(group=df.groupby('Ticker').cumcount().add(1))
.pivot(index='Ticker', columns='group', values='Price')
.add_prefix('Price_of_the_#')
)
输出:
group Price_of_the_#1 Price_of_the_#2 Price_of_the_#3
Ticker
Apple 10 5 30
MSFT 20 10 50
推荐阅读
- javascript - 如何使用 - jspdf.loadFile?
- flutter - 如何在 Flutter 中使用 dart:ffi?
- ruby-on-rails - Nginx/Puma/Rails - WebSocket 连接到'
' 失败:WebSocket 在连接建立之前关闭 - javascript - Javascript Sticky Element onscroll 避免跳转
- wildfly-10 - WildFly 10.1 无法创建日志数据源来存储消息
- excel - 为什么我的用户表单值没有更新查找工作表中的单元格?
- android - 应用程序作为 APK 运行,但通过 Play 商店发布时崩溃
- python - 我如何刮掉这个元素?
- spring - 使用spring从数据库一次加载数据并始终可用并在JSP中显示
- python - 更改 KDE matplotlib.plot 的颜色和有边顺序