递增不存在索引的列表索引



我正在尝试遍历数据集的行,并递增新创建列表的索引。我知道我目前正在尝试增加一个不存在的索引,但我非常感谢任何试图完成类似事情的帮助。

这是我的代码片段:

attack_year_type = []
year_type_counter = []
for _, event in main_df.iterrows():
attack_year_type.append((event['iyear'], event['attacktype1_txt']))
year_type_counter[int(event['iyear'])][event['attacktype1_txt']] += 1

我认为你最好year_type_counter成为dicts的dict。 在这种情况下,您可以使用defaultdict来完成您想要的事情。

from collections import defaultdict
year_type_counter = defaultdict(lambda: defaultdict(int))
attack_year_type = []
for _, event in main_df.iterrows():
attack_year_type.append((event['iyear'], event['attacktype1_txt']))
year_type_counter[int(event['iyear'])][event['attacktype1_txt']] += 1

你可以做的是初始化列表,如下所示

attack_year_type = [None]*(main_df.count())
year_type_counter = [None]*(main_df.count())

然后,根据索引修改元素。

最新更新