Pandas Dataframe 输出两位小数

Pandas Dataframe Output in two decimal places

我有以下代码,想将输出(斜率、截距、r_value、p_value、str_err)四舍五入到小数点后两位。我如何在此代码中执行此操作?


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)

您可以使用函数round(variable,number_of_decimal_places)对变量进行舍入。

在您的用例中,您可以使用以下语法对字典值进行舍入:

#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)

您可以使用 round() 直接舍入这些值。

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)

或者,如果您要将结果列表转换为数据框,则可以在列或整个数据框上使用 pandas.round() 来舍入值(参见此处:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html

df.round(2)

这会将数据框中的所有值四舍五入到小数点后两位。如果要排除列,请使用 loc[].

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