使用read_csv时传入squeeze参数报错,原因是什么?
报错原因分析与解决方案
报错原因
read_csv()的squeeze参数在新版pandas中已被移除。该参数曾用于将单列DataFrame自动转换为Series,但pandas后续版本弃用了这一参数,因此传入squeeze=True会触发TypeError,提示存在未识别的关键字参数。
解决方案
方案1:读取后直接提取单列
读取DataFrame后,通过列名或位置索引提取目标列,直接得到Series:
# 通过列名提取 alcohol = pd.read_csv('https://andybek.com/pandas-drinks', usecols=['country','wine_servings'], index_col='country')['wine_servings'] # 通过位置索引提取(适用于不确定列名的场景) alcohol = pd.read_csv('https://andybek.com/pandas-drinks', usecols=['country','wine_servings'], index_col='country').iloc[:, 0]
方案2:使用squeeze()方法显式转换
读取DataFrame后调用squeeze()方法,将单列DataFrame转为Series:
alcohol = pd.read_csv('https://andybek.com/pandas-drinks', usecols=['country','wine_servings'], index_col='country').squeeze()
内容的提问来源于stack exchange,提问作者Ashutosh Bhoi
相关产品推荐
相关产品推荐

