pythonjupyter-notebookdivide

Python - Can't divide column values


I'm trying to divide each value of a specific column in df_rent dataframe by simply accessing each value and divide by 1000. But it's returning an error and I cannot understand the reason.

Type of the column is float64.

for i in df_rent['distance_new']:
    df_rent[i] = df_rent[i] / 1000
    print(df_rent[i])

Solution

  • the error is because if you loop over df_rent['distance_new'],the i assigned will be the value of your first cell in 'distance_new', then the second, then the third, it will not be a pointer index. what you should do is rather simple

    df_rent['distance_new']/=1000
    

    In case someone doesn't understand, /= operator takes the value, divides by RHS, then replace the LHS value by the result. the LHS can be int, float, or in this case a whole column. this solution also works on multiple column if you slice them correctly, will be something like

    df_rent.loc[:,['distance_new','other_col_1','other_col2']]/=1000