Python中Series对象无stack属性报错问题求助
问题解决思路
错误根本原因:
pd.Series对象从来就没有stack()方法,这个方法是pd.DataFrame独有的,和你用的Python版本(8/11/12)完全无关,不管哪个版本的Pandas都遵循这个设计。你的代码问题:你一开始就把数据存在
Series里,调用apply之后返回的结果还是Series,自然找不到stack属性。修复方案:
- 把
apply后的结果先转成DataFrame再调用stack:df = pd.Series(sorted(glob(user_location))) # 先转成DataFrame再执行stack操作 df = df.apply(get_image_path2, args=(sample_location,)).to_frame().stack(future_stack=True) df = df.rename_axis(index=['users', 'samples']) - 或者调整
get_image_path2函数的返回格式,让apply直接生成DataFrame而非Series。比如如果函数返回的是每个用户对应的多个样本路径列表,可以用pd.DataFrame.from_records来转换结构。
- 把
补充说明:如果
get_image_path2返回的是列表类型,也可以用explode()来展开数据,不过这和stack的作用略有不同,需要根据你最终想要的索引结构选择。示例:df = pd.Series(sorted(glob(user_location))) df = df.apply(get_image_path2, args=(sample_location,)).explode() # 再手动设置所需的索引层级
内容的提问来源于stack exchange,提问作者naibai
相关产品推荐
相关产品推荐

