【问题标题】:Unable to convert pandas dataframe into 2 decimal places无法将熊猫数据框转换为小数点后 2 位
【发布时间】:2018-09-25 12:39:25
【问题描述】:

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

df_survey 是我使用 pandas 库制作的数据框。 (我尝试将 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'),但值仍然是整数。

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

【问题讨论】:

  • 你能分享列的 dtypes ['非常感兴趣','有点感兴趣','不感兴趣'] 另外,你是否只有 3 行在 for 循环中按顺序循环?这不是很高效。
  • 分享一些样本输入和期望的输出?
  • @devssh 我的循环性能如何?
  • 因为 for 循环没有并行化,所以 dataframe["column"] 给出了一个 pd.Series 并且 pd.Series.apply 是并行的,因为它是矢量化的。

标签: python pandas


【解决方案1】:

以下是将 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 位。

【讨论】:

  • 为什么投反对票?这不是你问题的标题吗?
【解决方案2】:

您可以直接使用四舍五入 DataFrame df.round(2)

【讨论】:

  • 我使用了我的问题中描述的那种方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-12
相关资源
最近更新 更多