如何转换为“月末”?

Rna*_*nho 4 python time datetime pandas

我有几个当前包含所有月末数据的数据框。

我现在使用以下脚本导入财务数据:

import csv
import pandas as pd
import numpy as np
import urllib.request  

urllib.request.urlretrieve(  
    'http://chart.finance.yahoo.com/table.csv?s=^GSPC&a=4&b=1&c=2013&d=5&e=1&f=2016&g=m&ignore=.csv',
    'gspc.csv'
)

table = pd.read_csv('gspc.csv')

    Date    Open    High    Low Close   Volume  Adj Close
49  2012-05-01  1,398   1,415   1,292   1,310   4158095900  1,310
48  2012-06-01  1,310   1,363   1,267   1,362   4103472300  1,362
47  2012-07-02  1,362   1,392   1,325   1,379   3663113300  1,379
Run Code Online (Sandbox Code Playgroud)

正如我所说,我需要将这些数据放到月末。IE

    Date    Open    High    Low Close   Volume  Adj Close
49  2012-05-31  1,398   1,415   1,292   1,310   4158095900  1,310
48  2012-06-30  1,310   1,363   1,267   1,362   4103472300  1,362
47  2012-07-31  1,362   1,392   1,325   1,379   3663113300  1,379
Run Code Online (Sandbox Code Playgroud)

我试过

table['Date'] = pd.to_datetime(table['Date'])
table.set_index('Date').resample('M')
table
Run Code Online (Sandbox Code Playgroud)

但没有成功,虽然“M”应该是“月末频率”。

Iva*_*van 6

这应该是你要找的东西

table['Date'] = table['Date'] - pd.tseries.offsets.MonthEnd()
Run Code Online (Sandbox Code Playgroud)

  • 我认为应该是:`table.Date -= pd.offsets.MonthEnd()` (2认同)