【问题标题】:How to keep column name using group-by function in python? [duplicate]如何在python中使用group-by函数保留列名? [复制]
【发布时间】:2019-08-29 22:55:19
【问题描述】:

我有一个带有搜索流量的数据框,并编写了一个代码来获取每天的第一个和最后一个请求以及它们之间的时间差。

df = pd.read_csv("Testordner2/"+i, parse_dates=True)
df['new_time'] = pd.to_datetime(df['new_time'])
df['dates']= df['new_time'].dt.date
df['time'] = df['new_time'].dt.time
out = df.groupby(df['dates']).agg({'time': ['min', 'max']}) \
                                 .stack(level=0).droplevel(1)
out['min_as_time_format'] = pd.to_datetime(out['min'], format="%H:%M:%S")
out['max_as_time_format'] = pd.to_datetime(out['max'], format="%H:%M:%S")
out['wh'] = out['max_as_time_format'] - out['min_as_time_format']
out['wh'].astype(str).str[-18:-10]

这很好,我得到一个数据框out,看起来像:

                 min       max       wh
dates                                  
2005-09-06  07:41:18  21:59:57 14:18:39
2005-09-12  14:49:22  14:49:22 00:00:00
2005-09-19  11:08:56  11:24:05 00:15:09
2005-09-21  21:19:21  21:20:15 00:00:54
2005-09-22  19:41:52  19:41:52 00:00:00
2005-10-13  11:22:07  21:05:41 09:43:34
2005-11-22  11:53:12  21:21:22 09:28:10
2005-11-23  00:07:01  14:08:50 14:01:49
2005-11-30  13:42:48  23:59:19 10:16:31
2005-12-01  00:05:16  10:24:12 10:18:56
2005-12-21  17:38:43  19:26:03 01:47:20
2005-12-22  09:20:07  11:25:40 02:05:33
2006-01-23  07:46:20  08:01:52 00:15:32
2006-04-27  16:27:54  19:29:52 03:01:58
2006-05-11  12:48:34  23:10:44 10:22:10
2006-05-15  10:14:59  22:28:12 12:13:13
2006-05-16  01:14:07  23:55:51 22:41:44
2006-05-17  01:12:45  23:57:56 22:45:11
2006-05-18  02:42:08  21:48:49 19:06:41
2006-05-22  00:00:29  23:07:12 23:06:43
2006-05-23  02:14:55  22:35:04 20:20:09
2006-05-24  11:53:08  21:25:39 09:32:31
2006-05-25  01:20:38  22:14:55 20:54:17
2006-05-29  01:34:09  23:53:33 22:19:24

问题是我的数据框out 中需要一个列dates,但这不存在。我不知道为什么列名“dates”与其他列名“min”、“max”和“wh”的高度不同.. 我以前从未使用 groupby 遇到过这个问题,但以前从未使用过 eggfunction。不知道是不是这个问题的原因..

第二个问题:我想在wh 中建立每月工作时间的平均值。 我用:

out['month']= pd.PeriodIndex(out.dates, freq='M')
out2=out.groupby('month')['wh'].mean().reset_index(name='wh2')

但是wh 中的值不是数字数据,所以我不能使用mean。 如何转换整列?

【问题讨论】:

  • df = df.reset_index() 让你把它找回来
  • 谢谢!我编辑了我的帖子,因为我有第二个问题并且必须等待 90 分钟才能完成我的下一个问题。你也可以帮我解决这个问题吗?
  • 欢迎来到 Stack Overflow!如果您将第二个问题作为新问题单独发布,您更有可能获得第二个问题的答案。只需要再等几分钟......

标签: python python-3.x pandas dataframe group-by


【解决方案1】:

只需重置索引:

out.reset_index(inplace=True)

分组和平均日期时间:

grouper = out.groupby('month')
int_mean = grouper['wh'].apply(lambda x: x.astype(int).mean())
mean = int_mean.apply(pd.to_datetime)

【讨论】:

  • 谢谢!我编辑了我的帖子,因为我有第二个问题并且必须等待 90 分钟才能完成我的下一个问题。你能帮我解决这个问题吗?
  • @Melli 没问题,很乐意提供帮助。没问题,请查看最新编辑。
猜你喜欢
  • 1970-01-01
  • 2022-01-11
  • 1970-01-01
  • 1970-01-01
  • 2012-12-13
  • 2021-11-30
  • 2020-12-23
  • 1970-01-01
  • 2018-11-13
相关资源
最近更新 更多