Search code examples
pythonpandasdataframeaveragedata-analysis

How to find the average speed?


I want to calculate the average speed for each ID, i used this code

df_Speed=df2.groupby('ID').agg(Total_Speed=('speed Km/h', 'sum'),Total_steps=('ID', 'count')).reset_index()
df_Speed['Avg_Speed']=df_Speed['Total_Speed']/df_Speed['Total_steps']

df_Speed.head()

but i get inf as a speed !

ID       Total_Speed          Total_schritte    Avg_Speed
1817603  2199.422386          149               14.761224
1817615  inf                  1178              inf
1817679  inf                  452               inf
1817888  5436.540730          271               20.061036

how can i get the speed instead of this inf


Solution

  • You are reading the data, which has somehow created infinity. As you would know, infinity divided by some constant is still infinity.

    To fix this problem, you might want to tweak your data, or fill the infinities with average.

    import numpy as np
    # Replace inf with nan
    df['Total_Speed'].replace([np.inf, -np.inf], np.nan, inplace=True)
    # Replace nan with mean
    df['Total_Speed'].fillna(df['Total_Speed'].mean())
    

    Source: Dropping infinite values from dataframes in pandas?