[英]Calculate the percentage and store in a csv file using pandas
I have following df.我有以下 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
Now, Here I want to calculate the percentage of each feature with respect to counts_y
现在,我想计算每个特征相对于
counts_y
SO, the formula will be like ,所以,公式将是这样的,
1. (100/counts_y) * counts_x
2. (100/counts_y) * counts
Wnat to have a final dataframe like Wnat 有一个最终的数据框,比如
predictedfeature counts_per counts_x
100 90 20
kind of output.种输出。
Kindly help me with this ?请帮我解决这个问题?
I think you need:我认为你需要:
df["counts_x"] = df["counts_x"] * 100 / df["counts_y"]
df["counts_per"] = df["counts"] * 100/ df["counts_y"]
Well, the computation of the percentage is pretty simple.嗯,百分比的计算非常简单。 Just create two additional columns which store the computed results.
只需创建两个额外的列来存储计算结果。
countdata["counts_x"] = countdata["counts_x"] * 100 / countdata["counts_y"]
countdata["counts_per"] = countdata["counts"] * 100/ countdata["counts_y"]
Now, your dataframe has two more columns.现在,您的数据框还有两列。 If you don't require the already existing columns in your dataframe, just drop them.
如果您不需要数据框中已经存在的列,只需删除它们。 Otherwise, to write only the new columns to a csv, do the following:
否则,要仅将新列写入 csv,请执行以下操作:
cols = ["PredictedFeature", "counts_per", "counts_x"]
countdata.to_csv('data.csv', columns = cols)
Basically, you are choosing the columns which you want to write to your csv.基本上,您正在选择要写入 csv 的列。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.