首页 > 解决方案 > TypeError: 'int' 对象在遍历 pandas 列时不可迭代

问题描述

我有一个简单的用例。我想将文本文件读入 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")

标签: pythonpandasloopsiterationtypeerror

解决方案


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

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-block中打开它
但是如果你用这种方式打开它,不要忘记在你不再需要它之后关闭它。

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))

如果你想要 pandas 中列的唯一值,可以删除df['id'].unique(),使用,但你不需要在这里手动做所有事情,因为你想要实现的目标是groupby

grpd = df.groupby('id')  

这将返回一个 groupby-object,当您对其进行迭代时 ,它确实为您提供了 groupname和group 数据,因此您的带有两个变量的循环可以在这里工作:

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


推荐阅读