从类中的属性计算元素出现的百分比。蟒蛇

时间:2015-10-19 12:00:00

标签: python count counting

我有一个名为transaction的类,它具有这些属性

Transaction([time_stamp, time_of_day, day_of_month ,week_day, duration, amount, trans_type,
location])

数据集的一个例子就是这样

timestamp   time    date    weekday duration    amount  trans_type      location
1           0:07    3       thu      2                  balance         driveup
2           0:07    3       thu      6          20      withdrawal      campus a
3           0:20    1       tue      2          357     advance         driveup
4           0:26    3       thu      2          20      withdrawal      campus b
5           0:26    4       fri      2          35       deposit            driveup

有不同的交易类型。在trans_type中定义:

advance, balance, deposit, transfer, withdrawal 

如何计算交易的百分比类型?

例如,这将是结果列表:

[('advance', 20), ('balance', 20), ('deposit', 20), ('transfer', 0), ('withdrawal', 40)]

这就是我的尝试:

#percentage of the different types of transactions
advance = 0
balance = 0
deposit = 0
transfer = 0
withdrawal = 0
for element in range(len(atm_transaction_list)):
    for trans_type in element:
        if trans_type == 'advance':
            advance += 1
        elif trans_type == 'balance':
            balance += 1
        elif trans_type == 'deposit':
            deposit += 1
        elif trans_type == 'transfer':
            transfer += 1
        elif trans_type == 'withdrawal':
            withdrawal += 1

1 个答案:

答案 0 :(得分:0)

使用for element in range(len(atm_transaction_list)):,您将迭代范围内的整数。当您想要使用索引时,通常会使用此选项。但是,你不这样做。只需使用for transaction in atm_transaction_list:遍历事务列表本身。然后,每个transaction将成为Transaction个对象。

我还建议将结果存储在字典中,而不是存储在五个单独的引用中。然后,您可以随时添加键值。

result = {'advance':0, 'balance':0, 'deposit':0, 'transfer':0, 'withdrawal':0}
for element in atm_transaction_list:
    result[element.trans_type] += 1

这将为您提供一个字典,您可以使用result['advance']之类的内容访问该字典,以查看'advance'次交易的数量。

现在将每个密钥的值除以事务总数并乘以100得到百分比:

l = len(atm_transaction_list)
for key in result:
    result[key] = result[key] / l * 100