我的数据框中有一个“本科”系列,我正在尝试迭代并将逗号剩下的所有内容拆分为“Bachelor...”和“University Name”,但我遇到了 Python TypeError让它通过一个循环,它返回一个“浮动”对象,尽管它是一个字符串,但它是不可下标的。可能有一种更简单的方法来做我正在做的事情,但是我在不同的项目中使用了这种技术并且它成功了,所以我试图重用我所做的。编码:undergrad = df['Undergraduate'].str.split(',')返回:0 [Bachelor of Arts/Science, Shanghai Jiaotong ...]1 [Bachelor of Arts/Science, University of Flor...2 [Bachelor of Arts/Science, University of Cinc...3 [Bachelor of Arts/Science, Harvard University]4 [Bachelor of Arts/Science, University of Puge...并使用了这个循环:eduList = []for item in undergrad: school = item[0][1] eduList.append(school)返回此错误:TypeError Traceback (most recent call last)<ipython-input-6-4131c28b2fb3> in <module>() 2 3 for item in undergrad:----> 4 school = item[0][1] 5 eduList.append(school)TypeError: 'float' object is not subscriptable当我检查 dtypes 时,它也说对象。不确定是什么问题。在此先感谢您的帮助!
1 回答
慕村225694
TA贡献1880条经验 获得超4个赞
也许您的数据没有记录,您应该检查哪一行导致此错误。我发现你的代码可能没有达到你的目标。因为item[0][1]只代表一个字符如下:
import pandas as pd
Undergraduate_list = ["Bachelor of Arts/Science,Shanghai Jiaotong","Bachelor of Arts/Science,University of Flor..."]
df = pd.DataFrame({"Undergraduate":Undergraduate_list})
undergrad = df['Undergraduate'].str.split(',')
eduList = []
for item in undergrad:
print(item[0],item[0][1])
输出是:
Bachelor of Arts/Science a
Bachelor of Arts/Science a
如果你想获得学位,你可以这样做:
eduList,universityList = undergrad.str[0],undergrad.str[1]
print(eduList)
你会得到:
0 Bachelor of Arts/Science
1 Bachelor of Arts/Science
Name: Undergraduate, dtype: object
添加回答
举报
0/150
提交
取消