Given a CSV data frame that contains two columns "Start date" and "End date"
Start date End date
10/1/2017 15:23:25 10/1/2017 15:26:26
10/1/2017 15:42:57 10/1/2017 17:49:59
How do I convert this to a list with a two entry dictionary like this:
[{'start': datetime.datetime(2017, 10, 1, 15, 23, 25),
'end': datetime.datetime(2017, 10, 1, 15, 26, 26)},
{'start': datetime.datetime(2017, 10, 1, 15, 42, 57),
'end': datetime.datetime(2017, 10, 1, 17, 49, 59)}]
I'm close but not quite there:
import pandas as pd
# Create a Pandas DataFrame
df = pd.DataFrame({'Start Date': ['10/1/2017 15:23:25', '10/1/2017 15:42:57'],
'End Date': ['10/1/2017 15:26:26', '10/1/2017 17:49:59']})
# Create a list of dictionaries
list_of_dicts = []
# Loop over the DataFrame rows
for index, row in df.iterrows():
# Create a dictionary
dict_ = {'start': pd.to_datetime(row['Start Date']),
'end': pd.to_datetime(row['End Date'])}
# Append the dictionary to the list
list_of_dicts.append(dict_)
# Print the list of dictionaries
print(list_of_dicts)
Which gives me:
[{'start': Timestamp('2017-10-01 15:23:25'),
'end': Timestamp('2017-10-01 15:26:26')},
{'start': Timestamp('2017-10-01 15:42:57'),
'end': Timestamp('2017-10-01 17:49:59')}]