python - 使用 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] 为嗯...谢谢。
解决方案
将最后一行代码更改为:
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]['用户名']。
推荐阅读
- python-3.x - 从嵌套字典的子集字典创建字典
- ios - 在 UICollectionView 中动态插入 Item
- amazon-web-services - CDK 将 API Gateway 堆栈拆分为 2 个小堆栈
- regex - 在 ibm watson 中实体的电子邮件识别模式中,术语 {2, } 在这里表示什么?
- assembly - 为什么在执行 pushl 指令时 rA:rB 是 2:8 而不是 2:f?
- git - 如何计算在 git 中更改一行的提交数?
- vb.net - 在多个控件内的禁用按钮上显示工具提示
- assembly - 需要一个很好的汇编语言代码解释(8086 微处理器)
- c++ - 生成 constexpr 字符串表,不能产生常量表达式
- r - 如何并行化crossprod以计算共现矩阵?