【发布时间】:2016-02-11 06:52:26
【问题描述】:
我正在尝试围绕各种资产的公共时间戳合并一组 DataFrame。数据集包含每小时数据,但每个资产的每小时时间戳略有不同。所以我将时间戳从纪元转换为日期时间并删除秒和分钟
market_trading_pair ohlcv_start_date next_future_timestep_return
7073 Poloniex_DOGE_BTC 1445392800 -0.023256
7074 Poloniex_DOGE_BTC 1445396400 0.023810
7075 Poloniex_DOGE_BTC 1445400000 0.000000
7076 Poloniex_DOGE_BTC 1445403600 -0.023256
7077 Poloniex_DOGE_BTC 1445407200 0.000000
使用此代码:
TS = 'ohlcv_start_date'
df[TS] = pd.to_datetime(df[TS], unit='s').dt.strftime('%Y-%m-%d %H:00:00')
print df.groupby('market_trading_pair').get_group('Poloniex_DOGE_BTC').head()[['market_trading_pair','ohlcv_start_date']]
market_trading_pair ohlcv_start_date next_future_timestep_return
7073 Poloniex_DOGE_BTC 2015-10-21 02:00:00 -0.023256
7074 Poloniex_DOGE_BTC 2015-10-21 03:00:00 0.023810
7075 Poloniex_DOGE_BTC 2015-10-21 04:00:00 0.000000
7076 Poloniex_DOGE_BTC 2015-10-21 05:00:00 -0.023256
7077 Poloniex_DOGE_BTC 2015-10-21 06:00:00 0.000000
使用所需数据制作一个新的数据框:
timestamp DOGE
7073 2015-10-21 02:00:00 -0.023256
7074 2015-10-21 03:00:00 0.023810
7075 2015-10-21 04:00:00 0.000000
7076 2015-10-21 05:00:00 -0.023256
7077 2015-10-21 06:00:00 0.000000
然后我创建一个“骨架”时间帧 DataFrame,我将能够将所有数据帧合并到并合并一个帧以进行测试。
timeframe = pd.date_range(start=min_time, end=max_time, freq='H')
test = DataFrame(timeframe, columns=['timestamp'])
timestamp
0 2015-10-21 02:00:00
1 2015-10-21 03:00:00
2 2015-10-21 04:00:00
3 2015-10-21 05:00:00
4 2015-10-21 06:00:00
test = pd.merge(left=test, right=to_merge, left_on='timestamp',right_on='timestamp',how='left')
timestamp DOGE
0 2015-10-21 02:00:00 NaN
1 2015-10-21 03:00:00 NaN
2 2015-10-21 04:00:00 NaN
3 2015-10-21 05:00:00 NaN
结果是 nan 字段,我认为这可能是由于格式错误?但是我比较了时间戳字符串,结果是“真”
【问题讨论】:
-
我认为问题出在 dtypes -
to_merge中的列DOGE是字符串,下一列是datetime- 所以它不能合并。你能检查print to_merge.dtypes和print test.dtypes吗? -
危险!我想你明白了,先生
timestamp object DOGE float64 dtype: objecttimestamp datetime64[ns] dtype: object我如何将其中一种类型转换为其他类型?