如何遍历时间戳并创建df

时间:2019-02-26 21:27:17

标签: python json pandas

我正在尝试生成将被API接受的时间戳(看起来像字符串格式),然后遍历这些时间戳并创建DF。

这就是我现在所拥有的。

代码:

cg = CoinGeckoAPI()
cs = 'bitcoin'

start_dti = '1, 1, 2017'
end_dti = '1, 2, 2019'
index = pd.date_range(start_dti, end_dti)

// missing a way to loop over this data
data = cg.get_coin_history_by_id(cs, index)

df_pr = pd_json.json_normalize(data['developer_data'])

df = pd.DataFrame(data=[{'date' : index, 
                        cs: data['developer_data']['pull_request_contributors']}]).set_index('date')

我希望得到一个这样的表:

           bitcoin
2017-01-01  380
2017-01-02  385
...
2019-02-01  1050

最终解决方案:

appended_data = []
for d in index.strftime('%d-%m-%Y'):
    data = cg.get_coin_history_by_id(cs, str(d))
    history = pd.DataFrame(data=[{'date' : str(d), 
                                     cs: data['developer_data']['pull_request_contributors']}]).set_index('date')
    appended_data.append(history)

appended_data = pd.concat(appended_data)

1 个答案:

答案 0 :(得分:1)

您可以使用.date的str:

In [11]: [str(d) for d in index.date]
Out[11]: ['2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05', '2019-01-06', '2019-01-07', '2019-01-08', '2019-01-09', '2019-01-10', '2019-01-11', '2019-01-12', '2019-01-13', '2019-01-14', '2019-01-15', '2019-01-16', '2019-01-17', '2019-01-18', '2019-01-19', '2019-01-20', '2019-01-21', '2019-01-22', '2019-01-23', '2019-01-24', '2019-01-25', '2019-01-26', '2019-01-27', '2019-01-28', '2019-01-29', '2019-01-30', '2019-01-31', '2019-02-01']

您可以使用Apply,但是我更喜欢使用dict:

history = {}
for d in index.date
    data = cg.get_coin_history_by_id(cs, str(d))
    history[d] = pd_json.json_normalize(data['developer_data']
    # etc?

然后合并数据帧的结果字典。