合并和合并Excel文件的时间范围

问题描述 投票:0回答:1

我正在尝试将大约 15 个以上的 Excel 文件合并为一个大文件。还有时间不匹配的情况,我想将一些时间范围合并为一个。例如,如果您在一张工作表中有上午 10:15 - 上午 10:30 以及与该时间关联的值 A,而在另一张工作表中您有上午 10:00 - 上午 11 点以及关联的“余额”值 B,那么在合并中您可以有 10 :15am-10:30am 值 A 和 B,因为 B 也属于那个时间。

这是我到目前为止所拥有的,有助于将 Excel 文件合并为一个。但现在我在匹配时间范围方面遇到了困难,请帮忙!谢谢!

import os
import pandas as pd
path = os.getcwd()
files = os.listdir(path)
files
path = os.getcwd()
files = os.listdir(path)

files_csv = [f for f in files if f.endswith('.csv')]

dfs = []

for f in files_csv:
    data = pd.read_csv(f)
    dfs.append(data)

df = pd.concat(dfs, ignore_index=True)

print(df)
python pandas excel dataframe match
1个回答
0
投票

要解决您的问题,您需要确保 CSV 文件位于当前工作目录中。获得 CSV 文件后,您可以使用以下代码来合并它们并根据重叠的时间间隔对齐数据

import os
import pandas as pd

# Get the current working directory
path = os.getcwd()

# Get all the csv files in the directory
files_csv = [f for f in os.listdir(path) if f.endswith('.csv')]

# Initialize an empty list to store the dataframes
dfs = []

# Read each csv file and append the dataframe to the list
for f in files_csv:
    data = pd.read_csv(f)
    # Convert the time columns to datetime
    data['start_time'] = pd.to_datetime(data['start_time'])
    data['end_time'] = pd.to_datetime(data['end_time'])
    dfs.append(data)

# Concatenate all dataframes
df = pd.concat(dfs, ignore_index=True)

# Sort the dataframe by start_time
df = df.sort_values('start_time')

# Group the dataframe by overlapping time intervals and aggregate the values
df['interval'] = (df['start_time'].shift() != df['start_time']).cumsum()
df = df.groupby(['interval', 'start_time', 'end_time']).sum().reset_index()

# Print the merged dataframe
print(df)

将“start_time”和“end_time”替换为 CSV 文件中代表开始时间和结束时间的实际列名称。请随意提出更多问题,我希望这有帮助代码由Ipeleng Floyd Bela

© www.soinside.com 2019 - 2024. All rights reserved.