首页 > 解决方案 > 如何在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

标签: pythonpandasdataframe

解决方案


如果您的数据已经按日期排序:

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

推荐阅读