Python Pandas 数据合并与字符串分割错误解决
Python Pandas 数据合并与字符串分割错误解决
在使用 Pandas 进行数据合并和字符串分割时,可能会遇到以下错误:
import pandas as pd
growth = pd.read_excel('C:\test\data\DATA\Growth.xlsx')
disease = pd.read_csv('C:\test\data\DATA\Disease.txt', delimiter='\s+')
both=growth.merge(disease, on='TreeID')
both['Test'],both['County']=both['TestCounty'].str.split('.', 1)
print(both)
报错:
TypeError: StringMethods.split() takes from 1 to 2 positional arguments but 3 were given
原因:
报错的原因是 StringMethods.split() 函数只能接受 1 个或 2 个位置参数,但是你传递了 3 个参数。
解决方法:
在 str.split() 函数中,通过设置参数 n=1,可以确保只分割一次,并且使用 .str 属性将分割的结果分配给两个新的列。
both['Test'], both['County'] = both['TestCounty'].str.split('.', n=1).str
解释:
both['TestCounty'].str.split('.', n=1):使用str.split()方法以.为分隔符分割TestCounty列,并设置参数n=1,确保只分割一次。.str:使用.str属性获取分割后的结果。both['Test'], both['County'] = ...:将分割后的结果分配给Test和County两个新的列。
通过以上方法,就可以成功解决 TypeError: StringMethods.split() takes from 1 to 2 positional arguments but 3 were given 错误,并实现将 TestCounty 列分割成 Test 和 County 两个新的列。
原文地址: https://www.cveoy.top/t/topic/o8nl 著作权归作者所有。请勿转载和采集!