skip to Main Content

So I have this fine code:


import pandas as pd
import requests
from datetime import datetime

now = datetime.now()
dt_string = now.strftime("%Y-%m-%dT%H:00:00")

url = 'https://api.energidataservice.dk/dataset/Elspotprices?filter={%22PriceArea%22:[%22DK1%22]}&limit=50'
r = requests.get(url)
json = r.json()


# HourUTC   HourDK  SpotPriceDKK    SpotPriceEUR

df = pd.DataFrame(json['records'])
df2 = df.loc[df['HourDK'] == dt_string]
df2 = df2.astype({'SpotPriceDKK': 'float'})

print(df2['SpotPriceDKK'].values)

When running the program it’s giving me what I want, like this:

[1053.52002]

But I cant make it a variable and subtract and add to it. How can you change this?

2

Answers


  1. IIUC, you need to extract the single value. Your code returns a DataFrame, which you then slice as Series. You can directly get the value using squeeze:

    val = df.loc[df['HourDK'] == dt_string, 'SpotPriceDKK'].squeeze()
    

    Output: 1053.52002

    Login or Signup to reply.
  2. Assuming that you get only one number in you df2['SpotPriceDKK'], simply change the type of your variable to int or float:

    import pandas as pd
    import requests
    from datetime import datetime
    
    now = datetime.now()
    dt_string = now.strftime("%Y-%m-%dT%H:00:00")
    
    url = 'https://api.energidataservice.dk/dataset/Elspotprices?filter={%22PriceArea%22:[%22DK1%22]}&limit=50'
    r = requests.get(url)
    json = r.json()
    
    
    # HourUTC   HourDK  SpotPriceDKK    SpotPriceEUR
    
    df = pd.DataFrame(json['records'])
    df2 = df.loc[df['HourDK'] == dt_string]
    df2 = df2.astype({'SpotPriceDKK': 'float'})
    
    num = df2['SpotPriceDKK'].values
    num_float = float(num)
    print(num_float)
    

    Output:

    1053.52002

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search