Home > Back-end >  I would like to use a function to clean up this code
I would like to use a function to clean up this code

Time:05-11

Link to image with code that is repetitive

I am only a beginner and not sure how to go about doing this. Any help would be greatly appreciated and if you have any helpful resources for learning this type of thing please do share. Apologies for not adhering to the usual format of most other posts on here.

CodePudding user response:

List_of_urls = ["https:...", "https:..."]

for i in range(len(List_of_urls):
  url = List_of_urls[i]
  request = request.get(url)
  request = request.json()
  ...

or

def do stuff(url):
   do each of those lines

and then run that function 5 times or in a loop

CodePudding user response:

If you perform the same operations based on an input url, simply put those steps in a function.

def create_df(my_url):

    my_request = requests.get(my_url)
    my_request = my_request.json()
    my_df = pd.DataFrame(my_request['prices'])
    my_df.rename(columns = {0 : 'Date', 1 : 'Price'}, inplace=True)
    my_df['date'] = pd.to_datetime(my_df['Date'], unit='ms')
    my_df.set_index('date', inplace=True)
    my_df.drop(['Date'], axis=1, inplace=True)

    return my_df

my_urls = [btc_url, eth_url, bnb_url, xrp_url, ada_url]
my_dfs = []

for url in my_urls:
    my_dfs.append(create_df(url))
  • Related