-1

I have a numpy array that looks like this:

data = [{'DateTime': '2020-03-13T16:44:58-03:00', 'Hl': 81.5, 'Bl': 82.5}, 
        {'DateTime': '2020-03-13T16:44:58-03:00', 'Hl': 87.7, 'Bl': 2.94}]  

I want this to a pandas DataFrame that looks like

Index                 DataTime     Hl   Bl
1    2020-03-13T16:44:58-03:00   81.5 82.5
2    2020-03-13T16:44:58-03:00   87.7 2.94

The column names need to be generated from what is in the numpy array as they vary from array to array.

S3DEV
  • 8,768
  • 3
  • 31
  • 42
sjobyt
  • 1
  • 1
  • 1
    Does this answer your question? [Convert list of dictionaries to a pandas DataFrame](https://stackoverflow.com/questions/20638006/convert-list-of-dictionaries-to-a-pandas-dataframe) – foglerit Oct 09 '20 at 13:06

2 Answers2

0

It appears as though you were very nearly there. Just send your data array to the DataFrame constructor.

The DataFrame constructor can read a dict (or list of dicts, in this case) and uses the key/value pairs as columns/values, respectively. This means the column names will be dynamic as required, based on the keys of the dict.

import pandas as pd

data = [{'DateTime': '2020-03-13T16:44:58-03:00', 'Hl': 81.5, 'Bl': 82.5},
        {'DateTime': '2020-03-13T16:44:58-03:00', 'Hl': 87.7, 'Bl': 2.94}]

df = pd.DataFrame(data)

Output:

                    DateTime    Hl     Bl
0  2020-03-13T16:44:58-03:00  81.5  82.50
1  2020-03-13T16:44:58-03:00  87.7   2.94
S3DEV
  • 8,768
  • 3
  • 31
  • 42
0

you can also use

import pandas as pd

data = [{'DateTime': '2020-03-13T16:44:58-03:00', 'Hl': 81.5, 'Bl': 82.5},{'DateTime': '2020-03-13T16:44:58-03:00', 'Hl': 87.7, 'Bl': 2.94}]

df = pd.DataFrame.from_records(data)

these pandas.DataFrame.from_records and pandas.DataFrame.from_dict functions from pandas can be useful for you.

  • In my case the dictionary was not formatted correctly and the pandas.DataFrame.from_records fixed that. – sjobyt Oct 09 '20 at 17:14