【问题标题】:Truncate a time serie files and extract some descriptive variable截断时间序列文件并提取一些描述性变量
【发布时间】:2023-02-08 17:59:14
【问题描述】:

我有两个主要问题,我无法想象 python 中的解决方案。现在,我给你解释一下上下文。 一方面,我有一个数据集,其中包含一些带有 ID(1 ID = 1 患者)的日期点,如下所示:

ID Date point
0001 25/12/2022 09:00
0002 29/12/2022 16:00
0003 30/12/2022 18:00
... ....

另一方面,我有一个包含许多包含时间序列的文本文件的文件夹,如下所示:

0001.txt
0002.txt
0003.txt
...

这些文件具有相同的体系结构:ID(与数据集相同)在文件名中,文件内部结构如下(第一列包含日期和第二列值):

25/12/2022 09:00 155
25/12/2022 09:01 156
25/12/2022 09:02 157
25/12/2022 09:03 158
...

1/ 我想截断文本文件并仅检索 48H 数据集日期点之前的变量。

2 /为了进行一些统计分析,我想取一些值,例如这个变量的平均值或最大值,然后添加到这样的数据框中:

ID Mean Maximum
0001
0002
0003
... .... ...

我知道对你来说这将是一个微不足道的问题,但对我(python 代码的初学者)来说这将是一个挑战!

谢谢大家。

使用包含日期点的数据框管理时间序列并获取一些统计值。

【问题讨论】:

  • 请提供足够的代码,以便其他人可以更好地理解或重现问题。
  • “在 48H 数据集日期点之前”是什么意思?

标签: python file time-series text-files data-manipulation


【解决方案1】:

您可以使用 pandas 沿着这些方向做一些事情(我无法对此进行全面测试):

import pandas as pd
from pathlib import Path


# I'll create a limited version of your initial table
data = {
    "ID": ["0001", "0002", "0003"],
    "Date point": ["25/12/2022 09:00", "29/12/2022 16:00", "30/12/2022 18:00"]
}

# put in a Pandas DataFrame
df = pd.DataFrame(data)

# convert the "Date point" column to a datetime object
df["Date point"] = pd.to_datetime(df["Date point"])

# provide the path to the folder containing the files
folder = Path("/path_to_files")

newdata = {"ID": [], "Mean": [], "Maximum": []}  # an empty dictionary that you'll fill with the required statistical info

# loop through the IDs and read in the file
for i, date in zip(df["ID"], df["Date point"]):
    inputfile = folder / f"{i}.txt"  # construct file name
    if inputfile.exists():
        # read in the file
        subdata = pd.read_csv(
            inputfile,
            sep="s+",  # columns are separated by spaces
            header=None,  # there's not header information
            parse_dates=[[0, 1]],  # the first and second columns should be combined and converted to datetime objects
            infer_datetime_format=True
        )

        # get the values 48 hours after the current date point
        td = pd.Timedelta(value=48, unit="hours")
        mask = (subdata["0_1"] > date) & (subdata["0_1"] <= date + td)

        # add in the required info
        newdata["ID"].append(i)
        newdata["Mean"].append(subdata[2].loc[mask].mean())
        newdata["Maximum"].append(subdata[2].loc[mask].max())

# put newdata into a DataFrame
dfnew = pd.DataFrame(newdata)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-05
    • 1970-01-01
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2014-11-12
    • 2020-10-29
    • 2019-08-11
    相关资源
    最近更新 更多