1

このデータを毎月フォーマットしようとしていますが、その月の現在の日付までです。

import pandas as pd
import datetime
import quandl
import numpy as np

start = datetime.datetime(1993, 10, 2)
end = datetime.date.today()

df = quandl.get("FRED/DGS20", collapse="daily").reset_index()
df.index=np.arange(0,len(df))

print (df)

l=[]
for i in range(0,len(df)):
    if (df['DATE'].loc[i]).day == (df['DATE'].loc[len(df)-1]).day:
        l.append(df['DATE'].loc[i])

私が直面している問題は、その日付が週末または休日の場合、その月がスキップされることです。指定された日が N/A の場合、Python に月の最も近い適用可能な日を選択させるにはどうすればよいですか?

4

1 に答える 1

0

少し長いですが、for ループはありません。あなたの行の後に私のコードを挿入してくださいdf.index=np.arange(0,len(df))

years = pd.DatetimeIndex(df['DATE']).year
years_u = np.unique(years)
years_u_norm = years_u - years_u[0]
months = pd.DatetimeIndex(df['DATE']).month
months_u = np.unique(months)
months_u_norm = months_u - months_u[0]
days = pd.DatetimeIndex(df['DATE']).day
days_u = np.unique(days)
days_u_norm = days_u - days_u[0]
shp = (years_u_norm[-1]+1, months_u_norm[-1]+1, days_u_norm[-1]+1)
mat = np.full(shp, np.nan).ravel()

y_ind = years - years_u[0]
m_ind = months - months_u[0]
d_ind = days - days_u[0]
inds = np.vstack([y_ind[np.newaxis], m_ind[np.newaxis], d_ind[np.newaxis]])

inds2 = np.ravel_multi_index(inds, shp)
inds_grid = np.indices(shp)[2].ravel()
mat[inds2] = inds_grid[inds2]
start_ind = np.ravel_multi_index([[start.year - years_u[0]], [start.month - months_u[0]], [start.day - days_u[0]]], shp)
mat[:start_ind] = np.inf
end_ind = np.ravel_multi_index([[end.year - years_u[0]], [end.month - months_u[0]], [end.day - days_u[0] + 1]], shp)
mat[end_ind:] = np.inf

mat = mat.reshape(shp)
dist = np.absolute(mat - np.full(shp, end.day-1))

min_dist = np.nanargmin(dist, axis=2) + 1
inds_f = np.unique(np.ravel_multi_index(inds[:-1, :], shp[:-1]))
res_inds = np.indices(min_dist.shape)
res_y = res_inds[0].ravel()[inds_f] + years_u[0]
res_m = res_inds[1].ravel()[inds_f] + months_u[0]
res_d = min_dist.ravel()[inds_f]

df = pd.DataFrame({'year': res_y,
                   'month': res_m,
                   'day': res_d})
print(df)
于 2016-11-23T12:53:35.853 に答える