Python:如何对熊猫字典的功能进行矢量化

时间:2020-08-17 03:45:07

标签: python pandas optimization vectorization

如何使用涉及生成/构建字典的熊猫矢量化或numpy矢量化?因此,当前,我只是使用df.itertuples实现了对数据的迭代。想知道我是否可以使用熊猫矢量化对其进行优化,但出现错误unhashable type: 'numpy.ndarray''Series' objects are mutable, thus they cannot be hashed。我完全理解为什么,因为它们是易变的对象。但是,如何使用pandas或numpy向量化实现下面类似的示例?可能吗即使是这样,它的性能也会有所不同吗?

让我们考虑一个简单的代码,在其中遍历数据帧,然后收集直到该行为止的数据:

import pandas as pd
from collections import defaultdict

FILENAME = "data.csv"

class Group():
    def __init__(self):
        self.symbol = None
        self.groups = defaultdict(int)

    def update(self, order, symbol, group, quantity):
        self.groups[group] += quantity

    def __repr__(self):
        return f"{self.groups}"

def method1():
    df = pd.read_csv(FILENAME)
    data = defaultdict(Group)
    for (i, order, symbol, group, quantity) in df.itertuples():
        data[symbol].symbol = symbol
        data[symbol].update(order, symbol, group, quantity)
        print(f"Symbol {symbol} current data: {data[symbol]}")

method1()

示例data.csv具有:

order,symbol,group,quantity
0,A,4,800
1,A,9,500
2,C,1,200
3,C,3,-900
4,D,7,-600
5,B,9,900
6,B,9,300
7,C,7,100
8,C,8,500
9,C,6,-900

样本输出:

Symbol A data: defaultdict(<class 'int'>, {4: 800})
Symbol A data: defaultdict(<class 'int'>, {4: 800, 9: 500})
Symbol C data: defaultdict(<class 'int'>, {1: 200})
Symbol C data: defaultdict(<class 'int'>, {1: 200, 3: -900})
Symbol D data: defaultdict(<class 'int'>, {7: -600})
Symbol B data: defaultdict(<class 'int'>, {9: 900})
Symbol B data: defaultdict(<class 'int'>, {9: 1200})
Symbol C data: defaultdict(<class 'int'>, {1: 200, 3: -900, 7: 100})
Symbol C data: defaultdict(<class 'int'>, {1: 200, 3: -900, 7: 100, 8: 500})
Symbol C data: defaultdict(<class 'int'>, {1: 200, 3: -900, 7: 100, 8: 500, 6: -900})

1 个答案:

答案 0 :(得分:0)

IIUC,groupby()是合适的。数据帧df是根据上面的data.csv定义的。

g = df.groupby('symbol')[['group', 'quantity']]
g.groups

{'A': Int64Index([0, 1], dtype='int64'),
 'B': Int64Index([5, 6], dtype='int64'),
 'C': Int64Index([2, 3, 7, 8, 9], dtype='int64'),
 'D': Int64Index([4], dtype='int64')}

# get keys like this:
g.groups.keys()

dict_keys(['A', 'B', 'C', 'D'])

我们可以看到有关特定群体的更多信息; get_group('C')看起来像示例输出的最后一行。将g.get_group('C').to_dict()用于相关版本。

print(g.get_group('C'))
   group  quantity
2      1       200
3      3      -900
7      7       100
8      8       500
9      6      -900