无法将熊猫数据帧转换为 2 位小数



我是Python编程的新手。目前,我尝试制作一个能够在条形图顶部以小数点后 2 位显示百分比的图表。

df_survey是我使用熊猫库制作的数据帧。(我尝试将 datafame df_survey_sort复制到df_survey_pct中,但是当我在df_survey_pct中进行更改时,df_survey_sort也会更改......有人可以向我解释为什么会发生这种情况。因此,我执行以下操作以使df_survey_sort和df_survey_pct不会相互压倒(

df_survey = df_survey[['Very interested','Somewhat interested','Not interested']]
df_survey_sort = df_survey.sort_values(by='Very interested', ascending=0)
#df_survey_pct = df_survey_sort
df_survey_pct = df_survey.sort_values(by='Very interested', ascending=0)
total_ds = df_survey_sort.sum(axis=1)
for i in range(0,df_survey_sort.shape[0]):
df_survey_pct.iloc[i][0] = round(df_survey_sort.iloc[i][0]/total_ds[i]*100,2)
df_survey_pct.iloc[i][1] = round(df_survey_sort.iloc[i][1]/total_ds[i]*100,2)
df_survey_pct.iloc[i][2] = round(df_survey_sort.iloc[i][2]/total_ds[i]*100,2)

这是df_survey_pct的数据类型

Very interested        int64
Somewhat interested    int64
Not interested         int64
dtype: object

当我执行print(df_survey_pct)时,每个单元格的值不在小数位。

我什至尝试df_survey_pct = df_survey_pct.round(2)df_survey_pct = df_survey_pct.astype('float')但是该值仍然是整数。

因此,我只能在条形图中显示整数百分比。

以下是将 np.float64 列转换为 2 位小数

位的方法
df_survey["some_column_with_too_many_decimal"] = df_survey["some_column_with_too_many_decimal"].apply(lambda x: int(x*100)/100)

此外,如果您需要,请仅选择该列中的某些行,请在每行上使用df.loc而不是 iloc,因为 df 可能有太多行。

df.loc[(df["column1"]>0), ["column2", "column3"]]

df.loc[(df["column1"]>0), "column2", "column3"]

loc 的第一个参数是要筛选的条件列表,第二个参数是要选择的列,然后您可以使用 apply 更新它们,如上所示。

如果要使用舍入,可以将值四舍五入,然后乘以 100,转换为 int 并除以 100,使其十进制后 2 位。round 函数不会因为值在数据帧中的存储方式而将其限制为小数点后 2 位。

您可以使用以下方法直接舍入数据帧df.round(2)

最新更新