Home > OS >  Pandas Dataframe Output in two decimal places
Pandas Dataframe Output in two decimal places

Time:03-31

I have below code and want to round the output (slope, intercept, r_value, p_value, str_err) into 2 decimal places. How can I do it within this code?


for x_col in x_vars:
    for y_col in y_vars:
        
        result_dict = {}
        
        temp_df = df[[x_col, y_col]]
        temp_df = temp_df.dropna(how='any')
        
        print(x_col)
        x = temp_df[x_col]
        y = temp_df[y_col]
        
        slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
        result_dict['x_col'] = x_col
        result_dict['y_col'] = y_col
        
        result_dict["slope"] =slope
        result_dict["intercept"] =  intercept
        result_dict["r-value"] = r_value,
        result_dict["p-value"] = p_value, 
        result_dict["std"] = std_err
        
        result_list.append(result_dict)

CodePudding user response:

You can use the function round(variable,number_of_decimal_places) to round variables.

In your use case, you can use the following syntax to round the dictionary values:

#initialize empty dictionary for the rounded values
res_dict = dict()

for key in result_dict:
    if 'col' not in key:
        res_dict[key] = round(result_dict[key], 2)
    else:
        res_dict[key] = result_dict[key]

result_list.append(res_dict)

CodePudding user response:

You can use round() to directly round these values in place.

for x_col in x_vars:
    for y_col in y_vars:
        
        result_dict = {}
        
        temp_df = df[[x_col, y_col]]
        temp_df = temp_df.dropna(how='any')
        
        print(x_col)
        x = temp_df[x_col]
        y = temp_df[y_col]
        
        slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
        result_dict['x_col'] = x_col
        result_dict['y_col'] = y_col
        
        result_dict["slope"] = round(slope, 2)
        result_dict["intercept"] = round(intercept, 2)
        result_dict["r-value"] = round(r_value, 2)
        result_dict["p-value"] = round(p_value, 2) 
        result_dict["std"] = round(std_err, 2)
        
        result_list.append(result_dict)

Alternatively, if you are turning results list into a dataframe, you can use pandas.round() on a column or the entire dataframe to round the values (see here: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html)

df.round(2)

This will round all values in the dataframe to 2 decimal places. If you want to exclude columns use a loc[].

df.loc[:, ['slope', 'intercept', 'r-value', 'p-value', 'std']] = \
    df[['slope', 'intercept', 'r-value', 'p-value', 'std']].round(2)
  • Related