根据时间戳间隔创建 csv 文件的数据框

2024-04-14

我相信我的问题非常简单,并且一定有一个非常简单的方法来解决这个问题,但是由于我对Python,特别是pandas很陌生,我无法自己解决它。

我有数百个 csv 文件,格式如下:text_2014-02-22_13-00-00

所以格式是str_YY-MM-DD_HH-MI-SS。总而言之,每个文件代表一小时的间隔。

我想根据我将设置的间隔创建一个数据框Start_Time and End_Time,从该区间开始。所以,例如,如果我设置Start_Time如 2014-02-22 21:40:00 和End_Time如 2014-02-22 22:55:00 (我使用的时间格式只是为了说明示例),那么我将得到一个数据帧,它包含上述间隔之间的数据,该数据来自两个不同的文件。

所以,我认为这个问题可以分为两部分:

1 - 仅读取文件名中的日期

2 - 根据我设置的时间间隔创建一个数据帧。

希望我能够做到简洁和准确。我非常感谢您在这方面的帮助!也欢迎提供有关查找内容的建议


该解决方案有几个不同的部分。

  1. 创建文件夹路径
  2. 手动创建 3 个 csv 文件
  3. 将 csv 文件保存到列表中
  4. 编写自定义函数将文件名解析为日期时间对象
  5. 将所有内容放在一起,循环浏览文件夹中的 csv 文件
import os
import pandas as pd
import datetime

# step 1: create the path to folder
path_cwd = os.getcwd()

# step 2: manually 3 sample CSV files
df_1 = pd.DataFrame({'Length': [10, 5, 6],
                     'Width': [5, 2, 3],
                     'Weight': [100, 120, 110]
                    }).to_csv('text_2014-02-22_13-00-00.csv', index=False)
df_2 = pd.DataFrame({'Length': [11, 7, 8],
                     'Width': [4, 1, 2],
                     'Weight': [101, 111, 131]
                    }).to_csv('text_2014-02-22_14-00-00.csv', index=False)
df_3 = pd.DataFrame({'Length': [15, 9, 7],
                     'Width': [1, 4, 2],
                     'Weight': [200, 151, 132]
                    }).to_csv('text_2014-02-22_15-00-00.csv', index=False)

# step 3: save the contents of the folder to a list
list_csv = os.listdir(path_cwd)
list_csv = [x for x in list_csv if '.csv' in x]

print('here are the 3 CSV files in the folder: ')
print(list_csv)

# step 4: extract the datetime from filenames
def get_datetime_filename(str_filename):
    '''
    Function to grab the datetime from the filename.

    Example: 'text_2014-02-22_13-00-00.csv'
    '''
    # split the filename by the underscore
    list_split_file = str_filename.split('_')

    # the 2nd part is the date
    str_date = list_split_file[1]

    # the 3rd part is the time, remove the '.csv'
    str_time = list_split_file[2]
    str_time = str_time.split('.')[0]

    # combine the 2nd and 3rd parts
    str_datetime = str(str_date + ' ' + str_time)

    # convert the string to a datetime object
    # https://chrisalbon.com/python/basics/strings_to_datetime/
    # https://stackoverflow.com/questions/10663720/converting-a-time-string-to-seconds-in-python
    dt_datetime = datetime.datetime.strptime(str_datetime, '%Y-%m-%d %H-%M-%S')

    return dt_datetime

# Step 5: bring it all together

# create empty dataframe
df_master = pd.DataFrame()

# loop through each csv files 
for each_csv in list_csv:

    # full path to csv file
    temp_path_csv = os.path.join(path_cwd, each_csv)

    # temporary dataframe
    df_temp = pd.read_csv(temp_path_csv)

    # add a column with the datetime from filename
    df_temp['datetime_source'] = get_datetime_filename(each_csv)

    # concatenate dataframes
    df_master = pd.concat([df_master, df_temp])

# reset the dataframe index
df_master = df_master.reset_index(drop=True)

# examine the master dataframe
print(df_master.shape)
# print(df_master.head(10))
df_master.head(10)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

根据时间戳间隔创建 csv 文件的数据框 的相关文章

随机推荐