【问题标题】:Dictionary intersection based on keys, TypeError: list indices must be integers or slices, not Index基于键的字典交集,TypeError:列表索引必须是整数或切片,而不是索引
【发布时间】:2020-04-23 06:31:35
【问题描述】:

我正在使用一些不同的 youtube 数据集,我想查看哪些标签会随着时间的推移而持续存在,以及包含它们的视频数量,我使用的是 pandas,所以我可以轻松地绘制数据。

我已经提出了一个解决方案,但我不明白为什么它会起作用,或者更确切地说,为什么我认为相同的东西不起作用。

简化形式:

from collections import Counter
import pandas as pd

data = [
    ['a',
    'a',
    'a',
    'b',
    'b',
    'c'],
    ['a',
    'a',
    'b',
    'b',
    'b',
    'd']
]

res = []

for tags in data:
    cnt = Counter()
    for tag in tags:
        cnt[tag] += 1

    series = pd.Series()
    for tag in cnt.most_common():
        series[tag[0]] = tag[1]

    res.append(series)

temp = res[0].keys()
for each in res[1:]:
    temp &= each.keys()

try:
    for i in range(len(res)):
        res[i] = res[temp]
except Exception as ex:
    print(ex)

i = 0
for each in res:
    res[i] = each[temp]
    i += 1

print(res)

虚拟数据很简单,a 和 b 是相交的标签,但我不明白为什么每个都有效,但对于 i in range 不适用,除非我认为我可以保存 2 行我在范围内

输出:

list indices must be integers or slices, not Index
[a    3
b    2
dtype: int64, a    2
b    3
dtype: int64]

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    在发帖 10 秒后,我意识到我做错了什么,并迅速想删除它,但看到这已经有意见,当有人看到这个可耻的问题时感到恐慌......

    哦,好吧,为我辩护,我的大脑被炸了...编辑了标题,所以也许有人会找到我的代码并帮助他们

    我实际上并没有访问熊猫系列,而是列表本身......

    res[i] = res[temp]
    

    进入

    res[i] = res[i][temp]
    

    它可以工作......

    【讨论】:

      猜你喜欢
      • 2017-04-12
      • 2020-06-17
      • 2016-09-19
      • 2020-07-11
      • 2022-10-04
      • 2016-09-16
      • 1970-01-01
      • 2019-07-04
      相关资源
      最近更新 更多