gpt4 book ai didi

python - 如何在 pandas 中按日期分组并创建与日期关联的时间列

转载 作者:太空宇宙 更新时间:2023-11-03 20:27:49 26 4
gpt4 key购买 nike

我将此数据作为数据框,我想对日期进行分组并创建时间列:

        empIdn      date      time
36 517 2019-05-02 12:00:12
54 517 2019-05-02 12:32:05
223 517 2019-05-02 05:18:57
95 517 2019-05-02 05:23:02

我想要实现的是

      empIdn       date      timeA    timeB     timeC      timeD
36 517 2019-05-02 12:00:12 12:32:05 05:18:57 05:23:02

这是我迄今为止尝试过的:

datas = pd.read_csv(datFile, sep="\t",usecols=[0, skipinitialspace=True, names=['empId', 'date_time'])
df = pd.DataFrame(data = datas)
new = df['date_time'].str.split(" ", n = 1, expand = True)

df['empIdn'] = df['empId'].astype(int)
df['date'] = new[0]
df['time'] = new[1]
df['date'] = pd.to_datetime(df['date'])
df['time'] = pd.to_datetime(df['time'],format= '%H:%M:%S' ).dt.time

df.drop(columns=['date_time'], inplace = True)
df.drop(columns=['empId'], inplace = True)
df.sort_values('empIdn',inplace = True, ascending = True)

最佳答案

df3=df.groupby(['empIdn','date'])['time'].agg(list).reset_index(name='new')
df3 = df3.join(pd.DataFrame(df3.new.values.tolist(), df3.index).add_prefix('time_'))
df3.drop('new', axis=1, inplace = True)

关于python - 如何在 pandas 中按日期分组并创建与日期关联的时间列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57702217/

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