TypeError:遍历pandas列时不可迭代'int'对象

时间:2018-09-23 11:57:29

标签: python pandas loops iteration typeerror

我有一个简单的用例。我想将文本文件读入pandas文件,并遍历唯一的 id 来绘制 xy图 。 在许多其他项目上为我工作得很好,但现在我得到了TypeError: 'int' object is not iterable。 最初我得到TypeError: 'numpy.float64' object is not iterable,这就是为什么我将 id 的类型更改为 int 的原因(请参见代码)。但这也不起作用。我不明白为什么。有什么想法吗?

f = open(file,"r+")
with open(file,"r+") as f1:
    data10 = f1.read()
    TESTDATA = StringIO(data11)
df = pd.read_table(TESTDATA, sep=" ")
df.columns = ["x", "y", "id"]

#Astype because i got the error TypeError: 'numpy.float64' object is not iterable
df.id = df.id.astype(int)

#get unique values of column id
list1=df['id'].tolist()
list1=list(set(list1))
fig, ax = plt.subplots()
for i ,g in list1:
    x = df[df.id==i]['x']
    y = df[df.id==i]['y']
    g.plot(x='x',y='x', marker='o', ax=ax, title="Evaluation")

1 个答案:

答案 0 :(得分:0)

恕我直言,您的代码减少为

df = pd.read_table(file, sep=" ")

fig, ax = plt.subplots()
grpd = df.groupby('id')
for i, g in grpd:
    g.plot(x='x',y='y', marker='o', ax=ax, title="Evaluation")

说明:
我将逐步介绍代码:

f = open(file,"r+")

可以删除,在with块中打开文件之前无需打开文件
但是如果以这种方式打开它,别忘了在不再需要它后将其关闭

with open(file,"r+") as f1:
    data10 = f1.read()
    TESTDATA = StringIO(data11)

可以删除
1.奇怪地使用了data10,data11(将无法使用)和StringIO(太复杂了)
2.参见下一行代码

df = pd.read_table(file, sep=" ") 

,如果仅将TESTDATA替换为file,pandas可以非常强大地导入不同口味的文件...

df.columns = ["x", "y", "id"]

确定,如果您的文件还没有适合您需要的文件头,我建议您检查一下...

#Astype because i got the error TypeError: 'numpy.float64' object is not iterable
df.id = df.id.astype(int)

可以删除,因为您的错误与此无关,正如我昨天在评论中所述

#get unique values of column id
list1=df['id'].tolist()
list1=list(set(list1))

可以删除,如果您希望熊猫中一列的唯一值,请使用df['id'].unique(),但您不需要在此处手动完成所有操作,因为您想要的目标实现groupby

grpd = df.groupby('id')  

这将返回一个groupby对象,当您对其进行遍历时,确实会为您提供groupname 组数据,因此具有两个变量的循环将在此处工作:

fig, ax = plt.subplots()
for i, g in grpd:
    g.plot(x='x',y='x', marker='o', ax=ax, title="Evaluation")

并且要完整:您的额外内容

x = df[df.id==i]['x']
y = df[df.id==i]['y']

也可以删除,因为这也包含在分组背后的想法中。 (顺便说一句,您甚至没有在代码中使用它...)

最后,建议您阅读Python和pandas的基础知识,尤其是文件io https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files和pandas分组https://pandas.pydata.org/pandas-docs/stable/groupby.html