ValueError:无法插入ID,已经存在 - python

我有此数据:

ID   TIME
1    2
1    4
1    2
2    3

我想按ID对数据进行分组,并计算平均时间和每组的大小。

ID   MEAN_TIME COUNT
1    2.67      3
2    3.00      1

如果运行此代码,则会收到错误“ValueError:无法插入ID,已经存在”:

result = df.groupby(['ID']).agg({'TIME': 'mean', 'ID': 'count'}).reset_index()

参考方案

使用参数drop=True,它不会使用index创建新列,而是将其删除:

result = df.groupby(['ID']).agg({'TIME': 'mean', 'ID': 'count'}).reset_index(drop=True)
print (result)
   ID      TIME
0   3  2.666667
1   1  3.000000

但是如果需要索引中的新列,则首先需要rename旧列名:

result = df.groupby(['ID']).agg({'TIME': 'mean', 'ID': 'count'})
           .rename(columns={'ID':'COUNT','TIME':'MEAN_TIME'})
           .reset_index()
print (result)
   ID  COUNT  MEAN_TIME
0   1      3   2.666667
1   2      1   3.000000

如果需要通过多个列进行合并的解决方案:

result = df.groupby(['ID']).agg({'TIME':{'MEAN_TIME': 'mean'}, 'ID': {'COUNT': 'count'}})
result.columns = result.columns.droplevel(0)
print (result.reset_index())
   ID  COUNT  MEAN_TIME
0   1      3   2.666667
1   2      1   3.000000

ValueError:未知标签类型:'未知' - python

我尝试运行以下代码。顺便说一句,我是python和sklearn的新手。import pandas as pd import numpy as np from sklearn.linear_model import LogisticRegression # data import and preparation trainData = pd.read_csv…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

R'relaimpo'软件包的Python端口 - python

我需要计算Lindeman-Merenda-Gold(LMG)分数,以进行回归分析。我发现R语言的relaimpo包下有该文件。不幸的是,我对R没有任何经验。我检查了互联网,但找不到。这个程序包有python端口吗?如果不存在,是否可以通过python使用该包? python参考方案 最近,我遇到了pingouin库。

Python ThreadPoolExecutor抑制异常 - python

from concurrent.futures import ThreadPoolExecutor, wait, ALL_COMPLETED def div_zero(x): print('In div_zero') return x / 0 with ThreadPoolExecutor(max_workers=4) as execut…