1

3 つの pandas シリーズを使用する関数を作成しています。そのうちの 1 つは日付です。それらをリサンプリングできるデータフレームに変換できるようにする必要があります。問題は、単に次のことを行うときです。

>>> data.index = data.time
>>> df = data.resample('M')

次のエラーが表示されます。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/core/generic.py", line 234, in resample
    return sampler.resample(self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas/tseries/resample.py", line 100, in resample
    raise TypeError('Only valid with DatetimeIndex or PeriodIndex')
TypeError: Only valid with DatetimeIndex or PeriodIndex

これは、インデックスの型が datetime オブジェクトであっても、リサンプリングを行うときに、 の形式でない限り、datetime(x,x,x,x,x,x)正しく読み取れないためです。

したがって、それを使用すると、日付データは次のよう2011-12-16 08:09:07になります。

dates = data.time
date_objects = [datetime.strptime(dates[x], '%Y-%m-%d %H:%M:%S') for x in range(len(dates))]
data.index = date_objects 
df = data.resample('M')

私の問題は、これをオープンソースに使用していて、入力時に日付がどのような形式になるかがわからないことです。

だから私の質問は、文字列のフォーマット方法を知らずに、日付と時刻を含む文字列をdatetimeオブジェクトに変換するにはどうすればよいですか?

4

2 に答える 2

3

Pandas にはto_datetimeこの目的のための関数があり、Series に適用すると、値を datetime ではなく Timestamp に変換します。

data.time = pd.to_datetime(data.time)

df = data.set_index('time')

どこ:

In [2]: pd.to_datetime('2011-12-16 08:09:07')
Out[2]: datetime.datetime(2011, 12, 16, 8, 9, 7)

In [3]: s = pd.Series(['2011-12-16 08:09:07'])

In [4]: pd.to_datetime(s)
Out[4]:
0   2011-12-16 08:09:07
dtype: datetime64[ns]
于 2013-05-30T16:21:49.370 に答える