Home > Enterprise >  Extracting row data from a single column in a Python DataFrame
Extracting row data from a single column in a Python DataFrame

Time:11-09

Run the following code to identify the problem.

#Import the library
import amberelectric
from amberelectric.api import amber_api

import pandas as pd

configuration = amberelectric.Configuration(access_token =     'psk_954ef8ead8c4323b4fe73064186f6362')

# Create an API instance
api = amber_api.AmberApi.create(configuration)

sites = api.get_sites()

site_id = sites[0].id

today = api.get_prices(site_id)

#Print a DataFrame
data = pd.DataFrame(today)

#print(today)

print(type(data))

print(data.shape)

data1 = data.iloc[[0,1,2,3]]

print(data1)

Running the above code gives the following

<class 'pandas.core.frame.DataFrame'>
(48, 1)
                                               0
0  {'duration': 30.0, 'spot_per_kwh': 10.16542, '...
1  {'duration': 30.0, 'spot_per_kwh': 8.92124, 'p...
2  {'duration': 30.0, 'spot_per_kwh': 6.51428, 'p...
3  {'duration': 30.0, 'spot_per_kwh': 4.74366, 'p...

I understand that the result is a single column of 48 rows. But how can I extract the titles in the parenthesis (eg 'duration') from the single column? There are actually 12 headings that I would like to access and tabulate.

CodePudding user response:

I ran your code and realized although "today" looks like a list of dictionaries, it's actually not, so you need to convert to dictionary first before calling pd.DataFrame().

data = pd.DataFrame([i.to_dict() for i in today])

Now it's in tabular format

  • Related