Reputation: 93
I have a list of (user defined) objects known as "Instrument Measurements". These, have a title, accessible by Instrument_Measurement.name
and a series of data accessible by Instrument_Measurement.data
(both user defined methods).
These "Instrument Measurement" objects are items in a list called list_instr_objects
. The number of items ("Instrument Measurements") changes/cannot be hard-coded.
I need to create a Dataframe with column titles Instrument_Measurement.name
for each "Instrument Measurement" and data for that column of Instrument_Measurement.data
for that respective "Instrument Measurement".
I'm trying to do this by creating a dictionary of these objects and then converting that to a Dataframe:
from collections import defaultdict
testdict = defaultdict(list)
for i in range(len(list_instr_objects)):
testdict[list_instr_objects[i].name].append(list_instr_objects[i].data)
This doesn't work though, only the first data entry for each instrument is kept and the entries come out in a seemingly random order. I think this is because I'm passing a Series to the dictionary where I should be passing a list, but I can't think how else to do it/how to fix this.
Any thoughts?
Many thanks in advance.
Upvotes: 0
Views: 759
Reputation: 692
I think you can use OrderedDict to keep the order and use below code to generate the dataframe.
import pandas as pd
from collections import OrderedDict
testdict = OrderedDict()
for i in range(len(list_instr_objects)):
testdict[list_instr_objects[i].name] = (list_instr_objects[i].data)
combined_data = pd.DataFrame(testdict)
Upvotes: 1