按组

时间:2019-03-28 23:24:28

标签: python pandas data-science

我有一个当前看起来像这样的数据框:

image         source                               label
bookshelf     A                      [flora, jar, plant]
bookshelf     B                    [indoor, shelf, wall]
bookshelf     C             [furniture, shelf, shelving]
cactus        A                     [flora, plant, vine]
cactus        B                [building, outdoor, tree]
cactus        C                  [home, house, property]
cars          A          [parking, parking lot, vehicle]
cars          B                     [car, outdoor, tree]
cars          C            [car, motor vehicle, vehicle]

我想得到的是每个label中每个source的重复image的计数,即:

  1. 对于image 书架,来源 B C 共享“架子”标签(B + = 1; C + = 1)
  2. 对于image 仙人掌,没有来源共享相同的标签
  3. 对于image 汽车
  4. 来源 B C 共享标签“汽车”(B + = 1; C + = 1),并且来源 A C 共享标签“车辆”(A + = 1; C + = 1)

响应对象将是源共享标签的次数。在上面的示例中,(1)将 B C 计数分别增加1,而(3)将增加 B 和< em> C 各自计数1,而 A C 各自计数1:

{ 'A': 1, 'B': 2, 'C': 3 }

可复制的示例:

from pandas import DataFrame
df = DataFrame({
  'image': ['bookshelf', 'bookshelf', 'bookshelf',
            'cactus', 'cactus', 'cactus',
            'cars', 'cars', 'cars'],
  'source': ['A', 'B', 'C',
             'A', 'B', 'C',
             'A', 'B', 'C'],
  'label': [
    ['flora', 'jar', 'plant'],
    ['indoor', 'shelf', 'wall'],
    ['furniture', 'shelf', 'shelving'],
    ['flora', 'plant', 'vine'],
    ['building', 'outdoor', 'tree'],
    ['home', 'house', 'property'],
    ['parking', 'parking lot', 'vehicle'],
    ['car', 'outdoor', 'tree'],
    ['car', 'motor vehicle', 'vehicle']]
  },
  columns = ['image', 'source', 'label']
)

虽然每个源/图像通常有3个标签,但这并不能保证。

关于如何以良好的性能实现这一目标的任何想法?我有几百万条记录需要处理...

1 个答案:

答案 0 :(得分:3)

这应该可以完成工作:

from collections import Counter
sources = df['source'].unique()
output = {source: 0 for source in sources}
for image, sub_df in df.groupby('image'):
    counts = Counter(sub_df['label'].sum())
    for image, source, labels in sub_df.itertuples(index=False):
        for label in labels:
            output[source] += counts[label] - 1
print(output)