【问题标题】:Calculate the percentage and store in a csv file using pandas使用 pandas 计算百分比并存储在 csv 文件中
【发布时间】:2019-12-16 11:24:41
【问题描述】:

我有以下 df。

    PredictedFeature    counts_x        counts_y        counts
0   100                   1837            1224            850
1   200                    215             60              2
2   3600                   172             14             147
3   4600                   143             124            138
4   162                    30              16              20

现在,这里我要计算每个特征相对于counts_y的百分比

所以,公式会像,

  1.  (100/counts_y) * counts_x

  2.    (100/counts_y) * counts

希望有一个像

这样的最终数据帧
predictedfeature   counts_per      counts_x
   100                90             20

输出类型。

请帮我解决这个问题?

【问题讨论】:

  • 你尝试了什么?

标签: python pandas numpy


【解决方案1】:

我认为你需要:

df["counts_x"] = df["counts_x"] * 100 / df["counts_y"]

df["counts_per"] = df["counts"] * 100/ df["counts_y"]

【讨论】:

    【解决方案2】:

    嗯,百分比的计算非常简单。只需创建两个额外的列来存储计算结果。

    countdata["counts_x"] = countdata["counts_x"] * 100 / countdata["counts_y"]
    
    countdata["counts_per"] = countdata["counts"] * 100/ countdata["counts_y"]
    

    现在,您的数据框还有两列。如果您不需要数据框中已经存在的列,只需删除它们。否则,要仅将新列写入 csv,请执行以下操作:

    cols = ["PredictedFeature", "counts_per", "counts_x"]
    countdata.to_csv('data.csv', columns = cols)
    

    基本上,您正在选择要写入 csv 的列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-25
      • 1970-01-01
      • 2022-06-13
      • 2020-10-08
      • 2020-10-10
      • 1970-01-01
      • 2022-11-21
      • 2017-05-14
      相关资源
      最近更新 更多