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

2024-09-29 23:27:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

下面是我的代码片段:

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

Tags: 数据代码intxtevent列表fortype
2条回答

我认为你最好是做一个year_type_counterdictdict。在这种情况下,你可以用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())

然后,根据索引修改元素。你知道吗

相关问题 更多 >

    热门问题