将同一天的所有数据收集到一行 [英] Gather all data for same day into one row

查看:115
本文介绍了将同一天的所有数据收集到一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我拥有的数据可以简化为:

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
.
.
.

我正在使用python并尝试使用for循环和df.groupby而不成功(如果可能,当数据月份和年份更改时,我也需要使用它来工作).任何帮助将不胜感激!

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!

推荐答案

在这里,我使用for loop实现了您的目标.

Here, I achieve your goal using for loop.

我认为文件data.txt中包含您的数据:

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

这是代码:

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)))

输出

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

这篇关于将同一天的所有数据收集到一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆