【问题标题】:Pandas group by multiple columns and duplicate row with iterationPandas 按多列分组并通过迭代重复行
【发布时间】:2018-07-19 07:39:59
【问题描述】:

我有一个如下图所示的 pandas 数组。我想做以下事情:

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

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

我已经通过以下方法部分解决了这个问题:

# 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 年等)。有什么建议吗?

【问题讨论】:

    标签: python pandas duplicates conditional rows


    【解决方案1】:

    这就是我添加日期范围的方式。挑战是在年份列表中循环,因为这比行列表短。

    # 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
    

    【讨论】:

      猜你喜欢
      • 2022-01-27
      • 1970-01-01
      • 2018-03-20
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2019-02-16
      相关资源
      最近更新 更多