从库存数据框创建工作月末数据框

时间:2018-11-19 14:44:10

标签: python pandas

我是Python和Panda的新手。我正在尝试找出如何从库存数据框中创建一个新数据框的方法,该数据框中将只包含工作月末一天的行。

这是我的库存数据框:

apple = pd.read_csv("AppleStock.csv")
apple.head(10)

Date    Open    High    Low Close   Adj Close   Volume
0   2013-02-28  63.435715   63.981430   63.057144   63.057144   47.371712   80628800

1   2013-03-01  62.571430   62.597141   61.425713   61.495716   46.198692   138112100

2   2013-03-04  61.114285   61.171429   59.857143   60.007141   45.080402   145688900

3   2013-03-05  60.211430   62.169998   60.107143   61.591427   46.270584   159608400

4   2013-03-06  62.072857   62.178570   60.632858   60.808571   45.682465   115062500

5   2013-03-07  60.642857   61.715714   60.151428   61.511429   46.210499   117118400

6   2013-03-08  61.400002   62.204285   61.230000   61.674286   46.332844   97870500

7   2013-03-11  61.392857   62.715714   60.734287   62.552856   46.992863   118559000

8   2013-03-12  62.228573   62.697144   61.081429   61.204285   45.979744   116477900

9   2013-03-13  61.207142   62.071430   60.765713   61.192856   45.971165   101387300

这是我本月末数组的日子

month_index = pd.date_range('2013-02-28', '2018-02-28', freq='BM')

month_index
DatetimeIndex(['2013-02-28', '2013-03-29', '2013-04-30', '2013-05-31',
           '2013-06-28', '2013-07-31', '2013-08-30', '2013-09-30',
           '2013-10-31', '2013-11-29', '2013-12-31', '2014-01-31',
           '2014-02-28', '2014-03-31', '2014-04-30', '2014-05-30',
           '2014-06-30', '2014-07-31', '2014-08-29', '2014-09-30',
           '2014-10-31', '2014-11-28', '2014-12-31', '2015-01-30',
           '2015-02-27', '2015-03-31', '2015-04-30', '2015-05-29',
           '2015-06-30', '2015-07-31', '2015-08-31', '2015-09-30',
           '2015-10-30', '2015-11-30', '2015-12-31', '2016-01-29',
           '2016-02-29', '2016-03-31', '2016-04-29', '2016-05-31',
           '2016-06-30', '2016-07-29', '2016-08-31', '2016-09-30',
           '2016-10-31', '2016-11-30', '2016-12-30', '2017-01-31',
           '2017-02-28', '2017-03-31', '2017-04-28', '2017-05-31',
           '2017-06-30', '2017-07-31', '2017-08-31', '2017-09-29',
           '2017-10-31', '2017-11-30', '2017-12-29', '2018-01-31',
           '2018-02-28'],
          dtype='datetime64[ns]', freq=‘BM')

如何创建仅包含月末工作日行的新数据框?

1 个答案:

答案 0 :(得分:0)

将数据框中的日期转换为datetime。

apple.index = pd.to_datetime(apple['Date'])

使用您的month_index获取所需的行。

apple_month = apple.loc[month_index]