0

如何使用 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})
4

1 回答 1

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
于 2020-08-17T04:20:33.810 回答