Reputation: 107
The data I have can be simplified as:
Date;Temp
2019-06-20 00:00:00;18.44
2019-06-20 01:00:00;18.28
2019-06-20 07:00:00;18.23
2019-06-20 13:00:00;18.20
2019-06-21 02:00:00;18.48
2019-06-21 08:00:00;18.45
2019-06-21 14:00:00;18.36
2019-06-21 21:00:00;18.24
2019-06-22 01:00:00;18.15
2019-06-22 05:00:00;18.12
2019-06-22 12:00:00;18.06
2019-06-22 19:00:00;17.99
2019-06-23 00:00:00;17.35
2019-06-23 03:00:00;17.34
2019-06-23 08:00:00;17.31
2019-06-23 23:00:00;17.24
.
.
.
I would like to collect all the hourly temperatures for each day on the same row, and get a matrix something like:
2019-06-20 ;18.44;18.28;18.23;18.20
2019-06-21 ;18.48;18.45;18.36;18.24
2019-06-22 ;18.15;18.12;18.06;17.99
2019-06-23 ;17.35;17.34;17.31;17.24
.
.
.
I am using python and have tried with for
loops and df.groupby
without success (I would also need it to work for when the data changes month and year if possible). Any help would be greatly appreciated!
Upvotes: 0
Views: 58
Reputation: 1065
Here, I achieve your goal using for loop
.
I assume the file data.txt
contains your data:
data.txt
Date;Temp
2019-06-20 00:00:00;18.44
2019-06-20 01:00:00;18.28
2019-06-20 07:00:00;18.23
2019-06-20 13:00:00;18.20
2019-06-21 02:00:00;18.48
2019-06-21 08:00:00;18.45
2019-06-21 14:00:00;18.36
2019-06-21 21:00:00;18.24
2019-06-22 01:00:00;18.15
2019-06-22 05:00:00;18.12
2019-06-22 12:00:00;18.06
2019-06-22 19:00:00;17.99
2019-06-23 00:00:00;17.35
2019-06-23 03:00:00;17.34
2019-06-23 08:00:00;17.31
2019-06-23 23:00:00;17.24
Here is the code:
data = {}
with open("data.txt") as f:
for line in f:
if 'Date' not in line or 'Temp' not in line:
k, v = line.split()
temperature = v.split(';')[1]
if k not in data:
data[k] = [temperature]
else:
data[k].append(temperature)
for k, v in data.items():
print("{} ;{}".format(k, ";".join(v)))
Outputs
2019-06-20 ;18.44;18.28;18.23;18.20
2019-06-21 ;18.48;18.45;18.36;18.24
2019-06-22 ;18.15;18.12;18.06;17.99
2019-06-23 ;17.35;17.34;17.31;17.24
Upvotes: 1