I have the following got that gets a list of coins from a website. the output of this code gets printed in Jupypter. How can I assign the output to a variable/to a dataframe so that I can use it later as in input for another function?
import time
import requests
url = 'https://web-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
for start in range(1, 20000, 5000):
params = {
'start': start,
'limit': 5000,
}
r = requests.get(url, params=params)
data = r.json()
for number, item in enumerate(data['data']):
print(f"{start number:4} | {item['symbol']:5} | {item['date_added'][:10]}")
The output looks like this:
1 | BTC | 2013-04-28
2 | ETH | 2015-08-07
3 | USDT | 2015-02-25
I tried the Str() function in Python but it prints only the last coin in the list.
CodePudding user response:
You can create a list:
out = []
and then within the loop, append to it:
out.append({
'num': f'{start number:4}',
'symbol': f'{item["symbol"]:5}',
'date': item['date_added'][:10]},
)
import pandas as pd
import requests
url = 'https://web-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
out = []
for start in range(1, 20000, 5000):
params = {
'start': start,
'limit': 5000,
}
r = requests.get(url, params=params)
data = r.json()
for number, item in enumerate(data['data']):
out.append({
'num': f'{start number:4}',
'symbol': f'{item["symbol"]:5}',
'date': item['date_added'][:10]},
)
df = pd.DataFrame(out)
print(df.to_string(index=False))
Output:
num symbol date
1 BTC 2013-04-28
2 ETH 2015-08-07
3 USDT 2015-02-25
4 USDC 2018-10-08
5 BNB 2017-07-25
6 XRP 2013-08-04
7 BUSD 2019-09-20
8 DOGE 2013-12-15
CodePudding user response:
You can put your results in a list like so:
import time
import requests
url = 'https://web-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'
results = []
for start in range(1, 20000, 5000):
params = {
'start': start,
'limit': 5000,
}
r = requests.get(url, params=params)
data = r.json()
for number, item in enumerate(data['data']):
results.append({
"coin": item['symbol'],
"date": item['date_added']
})
You can then use the results list directly, or you can convert it to a dataframe:
import pandas as pd
results_df = pd.DataFrame(results)