python - 按组计算 Pandas Dataframe 中列表的重复项计数

标签 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]

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

  1. 对于图像书架,源BC共享“书架”标签(B+=1 ;C+=1)
  2. 对于图像仙人掌,没有来源共享相同的标签
  3. 对于图像汽车,来源BC共享标签“car”(B+=1 ; C+=1),来源AC共享标签“车辆”(A+=1; C+=1)

响应对象将是源共享标签的次数。在上面的示例中,(1) 会将 BC 计数各增加 1,(3) 会将 B 和 < em>C 各计数 1,AC 各计数 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 个标签,但这并不能保证。

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

最佳答案

这应该可以完成工作:

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)

关于python - 按组计算 Pandas Dataframe 中列表的重复项计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55408337/

相关文章:

python - 如何在 python3 代码中找到 python2 路径?

python - 错误的命名链接搜索和替换

python - 将 csv 目录读入 Pandas Dataframe

python - 从 R 到 Python : define multiple columns from multiple columns in a pandas dataframe

python - scikit-learn:支持向量机。精度和/或准确度?

data-science - QlikSense;表格的动态尺寸

machine-learning - 我应该如何分割数据以进行交叉验证和网格搜索?

python - 在 __init__ 之外初始化字段

python - 类设计: Last Modified

python - 当每个值都是字典时将数据框保存到 Excel