Alexander Thomsen
Alexander Thomsen

Reputation: 469

How to loop over timestamps and create df

I'm trying to generate timestamps that will be accepted by the API (looks like in string format) and then loop over these timestamps and create a DF.

This is what I have right now.

Code:

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')

I hope to get a table like this:

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

Final solution:

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)

Upvotes: 1

Views: 315

Answers (1)

Andy Hayden
Andy Hayden

Reputation: 375745

You can use str of the .date:

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']

You could use apply, but I'd prefer to use a 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?

Then concat the resulting dict of DataFrames.

Upvotes: 1

Related Questions