【问题标题】:how to retrieve the 3 months from each quarter hence increase df row number by 3 times. Pandas, Python如何从每个季度检索 3 个月,从而将 df 行数增加 3 倍。熊猫,蟒蛇
【发布时间】:2020-12-08 19:32:52
【问题描述】:

我有一个非常愚蠢的任务,但还没有找到方法, 我有一个巨大的df,这是头

    Deal Date Period Name  Price Quarter Start                   Quarter End
0  2011-11-01     2011-Q4  30.76    2011-10-01 2011-12-31 23:59:59.999999999
1  2011-11-01     2012-Q1  30.95    2012-01-01 2012-03-31 23:59:59.999999999
2  2011-11-01     2012-Q2  30.67    2012-04-01 2012-06-30 23:59:59.999999999
3  2011-11-01     2012-Q3  29.87    2012-07-01 2012-09-30 23:59:59.999999999
4  2011-11-01     2012-Q4  29.49    2012-10-01 2012-12-31 23:59:59.999999999

我希望有一个额外的列显示“月”,上面的 5 行将变为 15 行,例如初始行 0 将重复两次

    Deal Date Period Name  Price Quarter Start                   Quarter End  Month
0  2011-11-01     2011-Q4  30.76    2011-10-01 2011-12-31 23:59:59.999999999  10
1  2011-11-01     2011-Q4  30.76    2011-10-01 2011-12-31 23:59:59.999999999  11 
2  2011-11-01     2011-Q4  30.76    2011-10-01 2011-12-31 23:59:59.999999999  12

因为这 3 个月包含在第 4 季度... 其余行类似。

有没有简单的方法来实现这一点?谢谢

【问题讨论】:

    标签: python pandas datetime timestamp time-series


    【解决方案1】:

    您可以从 period 中提取季度值,然后使用只有 12 行包含季度 -> 月映射的数据框执行 pandas.merge

    简化示例代码:

    import pandas as pd
    
    df_test = pd.DataFrame({'quart':[1,2,3,4,1,2], 'val': ['a','b','c','d','e','f']})
    
    df_quart_to_month = pd.DataFrame({'quart':[1,1,1,2,2,2,3,3,3,4,4,4], 'month': [1,2,3,4,5,6,7,8,9,10,11,12]})
    
    df_with_months = df_test.merge(df_quart_to_month ,on='quart', how='outer')
    

    如果你想保持原来的顺序:

    df_with_months = df_test.reset_index().merge(df_quart_to_month ,on='quart', how='outer').set_index('index')
    
    df_sorted = df_with_months.sort_values(['index', 'month'], ascending=[True, True])
    

    或者,您可以根据季度将数据集拆分为 4 个数据帧,将每个子数据帧复制两次并添加相应的月份。然后将生成的 12 个子数据帧连接在一起。

    【讨论】:

    • 谢谢克里斯!我需要保持原始的行顺序,使用您的代码 Q1 值将出现在 Q2 之前等,仅供参考,数据来自几年
    • @neutralname 您可以按 2 列对生成的数据框进行排序,即按年排序,按季度排序。 df1.sort_values(['a', 'b'], ascending=[True, False])Source
    • 再次感谢克里斯,有没有办法保持原来的顺序?而不是按新标准排序
    • 您可以为此使用 DataFrame 的原始索引,即在合并时将索引保留为列,然后按原始索引(如果需要,按月份)Source 排序。我相应地更新了答案。如果回答了原始问题,请接受答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-23
    • 2020-05-12
    • 1970-01-01
    • 2022-11-14
    • 2022-01-11
    • 2021-08-04
    • 2021-11-09
    相关资源
    最近更新 更多