Pandas Dataframe 输出两位小数
我有以下代码,并希望将输出(坡度,截距,R_Value,p_value,str_err)折叠成2个小数点。我该如何在此代码中进行?
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用 round() 直接对这些值进行四舍五入。
或者,如果要将结果列表转换为数据帧,则可以在列或整个数据帧上使用 pandas.round() 来舍入值(请参阅此处:https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.round.html)
这个将四舍五入数据框中的值精确到小数点后两位。如果要排除列,请使用 loc[]。
You can use round() to directly round these values in place.
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)
This will round all values in the dataframe to 2 decimal places. If you want to exclude columns use a loc[].
您可以将函数
round(变量,number_of_decimal_places)
用于圆形变量。在您的用例中,您可以使用以下语法来绕过字典值:
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: