Pandas中apply结合iloc取最后一列报错too many indexers的问题咨询
问题解决:apply结合iloc取最后一列时的"too many indexers"错误
错误原因
当使用df.apply(..., axis=1)遍历行时,传入lambda的row是一维Series对象(代表DataFrame的一行),而非二维的DataFrame切片。iloc[:,-1]是针对二维结构(如DataFrame)的索引语法,需要两个维度的参数(行范围、列位置),但一维Series只有一个维度,因此会触发"too many indexers"错误。
修正方法
将row.iloc[:,-1]替换为针对一维Series的索引方式,取最后一个元素:
row.iloc[-1]:通过位置索引取最后一个元素row.iat[-1]:更高效的单个位置索引(仅用于取单个元素)row[-1]:直接利用Series的位置索引特性
修正后的调用代码:
df.apply(lambda row : find_grandchild_list(row.iloc[-1]), axis=1)
优化原函数(匹配预期输出)
原函数返回嵌套列表格式,可调整为直接返回孙代列表,更贴合你想要的最终格式:
def find_grandchild_list(child_val): # 找到所有以当前child为Parent的行,提取Child列作为孙代 grandchild_rows = df[df['Parent'] == child_val] return grandchild_rows['Child'].tolist()
生成最终层级格式
如果要直接生成类似预期的竖线分隔层级,可进一步处理:
# 新增孙代列 df['Grandchildren'] = df.apply(lambda row: find_grandchild_list(row.iloc[-1]), axis=1) # 拼接成完整层级字符串 df['Full_Hierarchy'] = df.apply(lambda row: ' | '.join([row['Parent'], row['Child']] + row['Grandchildren']), axis=1)
执行后df['Full_Hierarchy']的内容示例:
plant | cactus | aloe_vera | blue_cactus plant | algae | green_algae plant | tropical_plant | monstrera cactus | aloe_vera algae | green_algae tropical plant | monstrera | monkey_monstrera cactus | blue_cactus | light_blue_cactus monstrera | monkey_monstrera blue_cactus | light_blue_cactus | desert_blue_cactus_lightblue light_blue_cactus | desert_blue_cactus_lightblue
内容的提问来源于stack exchange,提问作者e_mauritius
相关产品推荐
相关产品推荐

