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={"PriceArea":["DK1"]}&limit=50'
r = requests.get(url)
json = r.json()
# dict_keys(['total', 'filters', 'limit', 'dataset', 'records'])
# 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 variabel and subtract and add to it. How can you change this?
CodePudding user response:
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
CodePudding user response:
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={"PriceArea":["DK1"]}&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