Python:如何在panda中对字典的函数进行矢量化



如何使用pandas矢量化或使用涉及生成/构建字典的numpy矢量化?所以目前,我只是使用df.itertuples实现了对数据的迭代。我想知道我是否可以使用熊猫矢量化来优化它,但我得到了unhashable type: 'numpy.ndarray''Series' objects are mutable, thus they cannot be hashed的错误。我完全理解为什么,因为它们是可变的对象。但是,我如何使用panda或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})

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

最新更新