我是Python编程的新手。目前,我尝试制作一个能够在条形图顶部的小数点后两位显示百分比的图形。
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')
,但该值仍为整数。
因此,我只能在条形图中显示整数百分比。
答案 0 :(得分:1)
您可以使用以下方法直接舍入DataFrame
df.round(2)
答案 1 :(得分:0)
这是将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,使其小数点后两位。由于值在数据框中的存储方式,舍入功能不将其限制为两位小数。