如何解决pandas中'Series'对象无'append'属性的AttributeError
问题解决:Series.append()报错的替代方案
问题原因
pandas 2.0及以上版本移除了Series.append()方法,你的线上课程内容基于旧版pandas,所以按照课程代码运行会触发AttributeError。
替代方案:使用pd.concat()
用pandas.concat()可以实现和原append()完全一致的合并效果,修改后的代码如下:
import pandas as pd students_classes = pd.Series({'Alice': 'Physics', 'Jack': 'Chemistry', 'Molly': 'English', 'Sam': 'History'}) kelly_classes = pd.Series(['Philosophy', 'Arts', 'Math'], index=['Kelly', 'Kelly', 'Kelly']) # 用pd.concat合并两个Series all_students_classes = pd.concat([students_classes, kelly_classes]) print(all_students_classes)
运行结果
执行后会得到你期望的合并结果:
Alice Physics Jack Chemistry Molly English Sam History Kelly Philosophy Kelly Arts Kelly Math dtype: object
补充说明
pd.concat()支持批量合并多个Series/DataFrame,只需将需要合并的对象放在一个列表中传入即可- 该方法会保留原Series的索引信息,和旧版
append()的行为完全一致
内容的提问来源于stack exchange,提问作者Derrin Matthew
相关产品推荐
相关产品推荐

