简体   繁体   English

将 dataframe 列从 object 转换为 timedelta 并求和

[英]Converting dataframe column from object to timedelta and summing

I have a Pandas dataframe that I'm segregating by month:我有一个 Pandas dataframe 我按月分隔:

months = [g for n, g in df.groupby(pd.Grouper(key='DATE',freq='M'))]

I'm then taking each month and summing the integers in a columns called PARTS RUN .然后,我每个月都会对名为PARTS RUN的列中的整数求和。

parts_run_month_sum = months[month]['PARTS RUN'].sum()

This is all working fine.这一切都很好。 The last thing I need to do is add the hours together from column HOURS RUN (HR:MIN) .我需要做的最后一件事是将HOURS RUN (HR:MIN)列中的小时数相加。 This column is an object data type.此列是 object 数据类型。 The data itself it a timedelta format, not datetime.数据本身是 timedelta 格式,而不是日期时间。 The format is like so: 02:11:40 , being hours:minutes:seconds.格式如下: 02:11:40 ,即小时:分钟:秒。

If I run the below line of code, it prints the correct index numbers related to the number of lines there happen to be for each month:如果我运行下面的代码行,它会打印与每个月碰巧有的行数相关的正确索引号:

for run_time in range(len(months[month]['HOURS RUN (HR:MIN)'])):
    print(run_time)

But if I try to get the lines of times themselves I receive a KeyError: 0 , although there is a key of 0 in each month that is returned in the above example.但是,如果我尝试自己获取时间线,我会收到KeyError: 0 ,尽管在上面的示例中每个月都会返回一个 0 键。

for run_time in range(len(months[month]['HOURS RUN (HR:MIN)'])):
    print(months[month]['HOURS RUN (HR:MIN)'][run_time])

What I'm actually looking for is how to sum the column of times, but because they are objects I cannot do this.我实际上正在寻找的是如何对时间列求和,但因为它们是我不能这样做的对象。

How can I convert a column with format hours:minutes:seconds to timedelta and sum the times?如何将格式为hours:minutes:seconds的列转换为 timedelta 并对时间求和?

I think you need:我认为你需要:

df['HOURS RUN (HR:MIN)'] = pd.to_timedelta(df['HOURS RUN (HR:MIN)'])

#if values are times
df['HOURS RUN (HR:MIN)'] = pd.to_timedelta(df['HOURS RUN (HR:MIN)'].astype(str))

I think instead your solution is possible aggregate sum :我认为您的解决方案可能是sum

df1 = df.groupby(pd.Grouper(key='DATE',freq='M'))['HOURS RUN (HR:MIN)'].sum()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM