Python 使用pandas计算百分比并存储在csv文件中

Python 使用pandas计算百分比并存储在csv文件中,python,pandas,numpy,Python,Pandas,Numpy,我有以下几个问题 PredictedFeature counts_x counts_y counts 0 100 1837 1224 850 1 200 215 60 2 2 3600 172 14

我有以下几个问题

    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
现在,我想计算每个特征相对于计数y的百分比

因此,公式如下:

  1.  (100/counts_y) * counts_x

  2.    (100/counts_y) * counts
Wnat有一个最终的数据帧,如

predictedfeature   counts_per      counts_x
   100                90             20
一种输出

请帮我做这个

我认为您需要:

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

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

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

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

countdata["counts_per"] = countdata["counts"] * 100/ countdata["counts_y"]
现在,您的dataframe还有两列。如果不需要dataframe中已经存在的列,只需删除它们。否则,要仅将新列写入csv,请执行以下操作:

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

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

您尝试了什么?