pandas显示百分数_如何使用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]

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值