如何使用Pandas的DataFrame计算百分比 [英] How to calculate percentage with Pandas' DataFrame

查看:2671
本文介绍了如何使用Pandas的DataFrame计算百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何用百分比将另一列添加到Pandas的DataFrame中?字典可以改变大小.

How to add another column to Pandas' DataFrame with percentage? The dict can change on size.

>>> import pandas as pd
>>> a = {'Test 1': 4, 'Test 2': 1, 'Test 3': 1, 'Test 4': 9}
>>> p = pd.DataFrame(a.items())
>>> p
        0  1
0  Test 2  1
1  Test 3  1
2  Test 1  4
3  Test 4  9

[4 rows x 2 columns]

推荐答案

如果确实要使用10的百分比,则最简单的方法是稍微调整数据摄入量:

If indeed percentage of 10 is what you want, the simplest way is to adjust your intake of the data slightly:

>>> p = pd.DataFrame(a.items(), columns=['item', 'score'])
>>> p['perc'] = p['score']/10
>>> p
Out[370]: 
     item  score  perc
0  Test 2      1   0.1
1  Test 3      1   0.1
2  Test 1      4   0.4
3  Test 4      9   0.9

对于实际百分比,相反:

For real percentages, instead:

>>> p['perc']= p['score']/p['score'].sum()
>>> p
Out[427]: 
     item  score      perc
0  Test 2      1  0.066667
1  Test 3      1  0.066667
2  Test 1      4  0.266667
3  Test 4      9  0.600000

这篇关于如何使用Pandas的DataFrame计算百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆