gpt4 book ai didi

excel - 计算列中的时间差并将其保存为具有多个电子表格的许多 excel 文件,PYTHON

转载 作者:行者123 更新时间:2023-12-04 20:26:23 33 4
gpt4 key购买 nike

我需要计算目录中包含多个电子表格的 n 个 excel 文件的时间差。
首先,我根据日期将数据框拆分为电子表格,然后检查 Door Name 列中是否有两个连续的行。是否不同,如果数据帧的长度是偶数,我最后计算了时间差。

第一步:

enter image description here

第二步:

enter image description here

我的代码:

import pandas as pd
import glob
import datetime
from tkinter import filedialog

pathEmp=Employees + "/*.xlsx" # Select directory using tkinter
for femp in glob.glob(pathEmp):
print('******\n')
name_file=os.path.split(femp)[-1]
print('Employee ',name_file)

xl = pd.ExcelFile(femp)
print('Sheet name: ',xl.sheet_names)
for sh in xl.sheet_names:
df = xl.parse(sh)
print('Processing: [{}] ...'.format(sh))
print('length : ',len(df))
df['Time'] = pd.to_datetime(df['Time'])
df['value'] = (df[['Door Name']] != df[['Door Name']].shift()).any(axis=1)
print('My df\n',df)
for i in range (len(df)):
if (len(df)) %2 == 0:
if (df.value.nunique() == 1):
df['Working hours'] = df['Time'].iloc[1::2].to_numpy() - df['Time'].iloc[::2]
Total = df['Working hours'].sum()
Total = '%02d:%02d:%02d' % (Total.days*24 + Total.seconds // 3600, (Total.seconds % 3600) // 60, Total.seconds // 60)
print('Working hours', Total)

预期输出:

enter image description here

如何保存列 Working hours在我目录中每个excel文件的每个电子表格中?

最佳答案

这是一个例子。

# your input
df = pd.DataFrame({
'DoorName': ('RDC_IN-1', 'RDC_OUT-1', 'RDC_IN-1', 'RDC_OUT-1', 'RDC_IN-1', 'RDC_OUT-1',
'RDC_IN-1', 'RDC_OUT-1', 'RDC_IN-1', 'RDC_OUT-1', 'RDC_IN-1'),
'Time': (datetime(2019, 9, 30, 17, 49, 6), datetime(2019, 9, 30, 17, 45, 51),
datetime(2019, 9, 30, 17, 45, 28), datetime(2019, 9, 30, 16, 37, 53),
datetime(2019, 9, 30, 15, 59, 53), datetime(2019, 9, 30, 9, 15, 0),
datetime(2019, 9, 27, 18, 25, 39), datetime(2019, 9, 27, 18, 27, 9),
datetime(2019, 9, 27, 12, 10, 33),
datetime(2019, 9, 27, 8, 42, 50), datetime(2019, 9, 27, 18, 24, 34)),
})

df['name'] = 'Arya Stark'
# generate date column from Time column
df['date'] = df['Time'].dt.strftime('%Y-%m-%d')

# open file for writing
with pd.ExcelWriter('output.xlsx') as writer:
# for each unique date
for u_date in df['date'].unique(): # type: str
# sub DataFrame from main DataFrame by date
df_by_date = df[df['date'] == u_date]
# date column is no longer needed
df_by_date = df_by_date.drop(columns=['date'])
# DoorName Cumulative sum + group by name (Arya Stark)
s = df_by_date['DoorName'].eq('RDC_IN-1').iloc[::].cumsum()
con = df_by_date.name.groupby(s).transform('nunique') == 1
# diff in seconds between RDC_IN and RDC_OUT for each couple
sec_df = df_by_date[con].groupby(s).agg({
'Time': lambda x: (x.iloc[0] - x.iloc[-1]).seconds
})

df_by_date = df_by_date.reset_index()
df_by_date = df_by_date.drop(columns=['index'])
df_by_date['WorkingHours'] = ''
# sum all seconds and convert to timedelta
working_hours = str(timedelta(seconds=int(sec_df['Time'].sum())))
# insert only in first row of sheet(as in your example)
df_by_date['WorkingHours'].loc[0] = working_hours
# append sheet by unique date
df_by_date.to_excel(writer, sheet_name=u_date, index=False)

你会看到预期的文件。查看评论 - 如果您需要一些更改,我相信您可以自定义它。希望这可以帮助。

关于excel - 计算列中的时间差并将其保存为具有多个电子表格的许多 excel 文件,PYTHON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59307376/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com