close

[Solved] ValueError: cannot insert ID, already exists

Hello Guys, How are you all? Hope You all Are Fine. Today I get the following error ValueError: cannot insert ID, already exists in python. So Here I am Explain to you all the possible solutions here.

Without wasting your time, Let’s start This Article to Solve This Error.

How ValueError: cannot insert ID, already exists Error Occurs?

Today I get the following error ValueError: cannot insert ID, already exists in python.

How To Solve ValueError: cannot insert ID, already exists Error ?

  1. How To Solve ValueError: cannot insert ID, already exists Error ?

    To Solve ValueError: cannot insert ID, already exists Error Use parameter drop=True which not create new column with index but remove it:

  2. ValueError: cannot insert ID, already exists

    To Solve ValueError: cannot insert ID, already exists Error Use parameter drop=True which not create new column with index but remove it:

Solution 1

Use parameter drop=True which not create new column with index but remove it:

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

But if need new column from index need rename old column names first:

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

Solution if need aggreagate by multiple columns:

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

Solution 2

I’d limit my groupby to just the TIME column.

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

   ID  MEAN_TIME  COUNT
0   1   2.666667      3
1   2   3.000000      1

Summery

It’s all About this issue. Hope all solution helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which solution worked for you? Thank You.

Also, Read