合并Excel文件的时间框架
我正在尝试把15个以上的Excel文件合并成一个大文件。现在有一些时间不匹配的问题,我想把一些时间段合并在一起。比如说,如果在一个表格里有10:15到10:30的时间段,且这个时间段对应的值是A,而在另一个表格里有10:00到11:00的时间段,且这个时间段对应的“余额”值是B,那么在合并的时候,你可以把10:15到10:30的时间段的值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)
1 个回答
-1
要解决你的问题,你需要确保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