首页 > 解决方案 > 如何选择格式为 yyyy-mm 的一组月份的 Pandas DataFrame 行?

问题描述

如何以 yyyy-mm 而不是 yyyy-mm-dd 格式选择一组月份的 Pandas DataFrame 行?给定以下代码:

import pandas as pd
import numpy as np


# Create a DataFrame of rows between 2018-01-01 and 2018-12-31
rng = pd.date_range('2018-01-01', periods=365, freq='D')
df = pd.DataFrame({ 'Date': rng}) 

# List of lists of quarters with start/end months/years
qtrs = [[[2018, 1], [2018, 3]], [[2018, 4], [2018, 6]], [[2018, 7], [2018, 9]], [[2018, 10], [2018, 12]]]

# Create a dictionary to store each quarter of data
folders = {}
# Cycle through each of the 4 quarters in 2018 and populate the folders dictionary
for el in qtrs:
    start_yr = el[0][0]
    start_mo = el[0][1]
    end_yr =  el[1][0]
    end_mo = el[1][1]

    # How can I modify this code below????
    folders['qtr_end_'+str(end_yr)+'_'+str(end_mo)] = df[(df['Date'] >= str(start_yr)+'-'+str(start_mo)) & (df['Date'] <= str(end_yr)+'-'+str(end_mo))]

我收到带有以下键的 DataFrames 字典:

dict_keys(['qtr_end_2018_3', 'qtr_end_2018_6', 'qtr_end_2018_9', 'qtr_end_2018_12'])

例如,以notfolders['qtr_end_2018_3']开头2018-01-01和结尾:2018-03-012018-03-31

        Date
0  2018-01-01
1  2018-01-02
2  2018-01-03
3  2018-01-04
4  2018-01-05
......
55 2018-02-25
56 2018-02-26
57 2018-02-27
58 2018-02-28
59 2018-03-01

我想要的输出是每个 DataFrame 都包含从季度开始到季度末的所有日期。例如,folders['qtr_end_2018_3']应该像这样开始和结束:

        Date
0  2018-01-01
1  2018-01-02
2  2018-01-03
3  2018-01-04
4  2018-01-05
......
85 2018-03-27
86 2018-03-28
87 2018-03-29
88 2018-03-30
89 2018-03-31

有没有一种方法可以修改我的代码以实现我想要的输出,同时保持每个季度的开始/结束月份/年份的输入列表?

标签: pythonpython-3.xpandasdataframedate

解决方案


如果您必须保留您的qtrs列表,使用 .dt 可能会有所帮助,这非常简单。看看这个 :

df[(df.Date.dt.year == 2018) & (df.Date.dt.month >= 1) & (df.Date.dt.month <= 3)]

上面的代码将根据您提供的年份和月份对您的日期进行子集化。

希望对您有所帮助,如果您需要更多详细信息,请告诉我。


推荐阅读