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

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

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

step1:

enter image description here

step2:

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

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

excel python-3.x pandas glob
1个回答
0
投票

这里是一个例子。

# 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)

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

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