如何使用 pandas 向量化或使用涉及生成/构建字典的 numpy 向量化?所以目前,我只是实现了对来自 using 的数据进行迭代df.itertuples。想知道我是否可以使用熊猫矢量化对其进行优化,但我得到了unhashable type: 'numpy.ndarray'or的错误'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})