Pandas按多个列分组并使用迭代重复行

2024-09-27 21:23:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫阵列,如下图所示。我想做以下事情:

  1. 按Exchange和Ticker对行进行分组(以确保它们是唯一的)
  2. 每行创建4个副本
  3. 对于每一行,将年份设置为不同的值(从变量)、2017、2016等

目的是显示5年的历史为每个股票,目前我的表只有一年的空间。我在这里研究过,但是我找不到这个组合。提前谢谢!在

enter image description here

我用以下方法部分解决了这个问题:

# Create four copies of the dataframe
Yr2_df = df1
Yr3_df = df1
Yr4_df = df1
Yr5_df = df1

# Merge the 5 dataframe into one combined dataframe
df = pd.concat([df1, Yr2_df, Yr3_df, Yr4_df, Yr5_df],axis=0).sort_index().reset_index(drop=True)

但是,这并没有提供日期范围(每行应该有不同的年份:2017年、2016年等)。有什么建议吗?在

enter image description here


Tags: the目的dataframedfindexexchange副本事情
1条回答
网友
1楼 · 发布于 2024-09-27 21:23:45

我就是这样添加日期范围的。这项挑战是循环使用年份列表,因为这比行列表要短。在

# Define list of years
years = [Year_Minus_1, Year_Minus_2, Year_Minus_3, Year_Minus_4, Year_Minus_5]

# Define index for iteration
index = df.index

# Import library for advanced iteration
import itertools

# Iterate over index and list of years so that we have one row per year for each ticker
for i, y in zip(index, itertools.cycle(years)):
     df.iloc[i, df.columns.get_loc('Year')] = y

相关问题 更多 >

    热门问题