I have two different CSVs with time series data. One Table is continuous, starting in 01.01.2017 at 00:00. From there each row represents one hour (1. Table). The data looks kind of like this:
- Table aka df1:
Date, Volume
2017-02-03 12-PM, 9787.51
2017-02-03 01-PM, 9792.01
2017-02-03 02-PM, 9803.94
2017-02-03 03-PM, 9573.99
The other table contains events that happened and are serialized by UNIX datetime in seconds. I was able to convert it to datetime and group it by hour with this code:
df['datetime'] = pd.to_datetime(df['created_utc'], unit='s')
df['datetime'] = pd.to_datetime(df['datetime'], format="%Y-%m-%d %I-%p")
df['date_by_hour'] = df['datetime'].apply(lambda x: x.strftime('%Y-%m-%d %H:00'))
This resulted in this data:
- Table aka df2:
created_utc, score, compound, datetime, date_by_hour
1486120391, 156, 0.125, 2017-02-03 12:13:11, 2017-02-03 12:00:00
1486125540, 1863, 0.475, 2017-02-03 13:39:00, 2017-02-03 13:00:00
1486126013, 863, 0.889, 2017-02-03 13:46:53, 2017-02-03 13:00:00
1486130203, 23, 0.295, 2017-02-03 14:56:43, 2017-02-03 14:00:00
Now I need to map the events (2.table) to the Time Series of the 1. Table. If multiple events happened in one hour, i need to make an addition of the scores and calculate the mean average of the compound. In the end i want to have a dataframe like this:
- Final Dataframe
Date, Volume, score, compound,
2017-02-03 12-PM, 9787.51, 156, 0.125,
2017-02-03 01-PM, 9792.01, 2726, 0.682,
2017-02-03 02-PM, 9803.94, 23, 0.295,
2017-02-03 03-PM, 9573.99, 0, 0,
I know my code below does not work and is wrong, but I wanted to show what I was thinking how I could achieve this. I thought I could loop through each row of my events table df2 and compare if the datetime matches. If so, I would calculate score and compound. The issue is that I know that one should not loop through a dataframe and I don't know how to loop through another dataframe at the same time and perform the right calculations based on the previous rows...
for index, row in df2.iterrows():
memory_score = 0
memory_compound = 0
if df1['Date'] == df2['date_by_hour']:
df1['score'] = row['score'] + memory_score
df1['compound'] = (row['compound'] + memory_compound) / 2
How can I get to my Final Dataframe? There must be some pandas magic that I could use to make this work and map the time series data to the right hours.
Thanks in advance and best regards
EDIT: THere can be an undefined number of events within one hour. I just chose 2 for this simple example but it could be 5000 or something or 0 in some cases.