Gather all data for same day into one row

无人久伴 提交于 2020-01-16 11:16:47

问题


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!


回答1:


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


来源:https://stackoverflow.com/questions/58902138/gather-all-data-for-same-day-into-one-row

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!