首页 > 解决方案 > 使用 iloc 时列表索引超出范围

问题描述

Tweets_df['question_user_id'] = 0
Tweets_df['question'] = 0
for i in range(Tweets_df.shape[0]): # Suppose Tweets_df is a dataframe with 100 rows
    if Tweets_df['main tweet (*** means no)'].iloc[i] == "***":
        if len(Tweets_df['reply_to'].iloc[i]) != 1:
            continue
        else:
            Tweets_df['question_user_id'].iloc[i] = Tweets_df['reply_to'].iloc[i][1]['username']

当解释器到达代码的最后一句时,出现 IndexError: list index out of range。有谁知道为什么会出现这样的错误?我没有看到错误,因为我认为 range(Tweets_df.shape[0]) 将具有 [0,1,...,99] 并且 iloc 对应于 [0,1,...,99] 为嗯...谢谢。

标签: pythonloopsindexoutofboundsexception

解决方案


将最后一行代码更改为:

Tweets_df['question_user_id'].iloc[i] = Tweets_df['reply_to'].iloc[i][0]['username']

因为仅当 Tweets_df['reply_to'] 的长度为 1 并且您尝试使用 Tweets_df['reply_to'].iloc[i 访问第二个元素(不存在)的“用户名”时才会执行 else 部分][1]['用户名']。


推荐阅读