python - Pandas:不一致的迭代问题
问题描述
import pandas as pd
d = {"col1":[1,2], "col2":[3,4]}
df = pd.DataFrame(data = d)
print(type(df.col1))
print(type(df["col1"]))
for index, col1 in df.col1.items():
pass
for index, col1 in df["col1"]:
pass
这输出:
<class 'pandas.core.series.Series'>
<class 'pandas.core.series.Series'>
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-a346dc42f5cd> in <module>
9 pass
10
---> 11 for index, col1 in df["col1"]:
12 pass
TypeError: cannot unpack non-iterable int object
但是为什么只能迭代1呢?两种对象类型与打印输出所指示的相同。
解决方案
他们在下面有不同的数据,这里看一下项目列表( .items 包括行):
In [177]: list(df.col1.items())
Out[177]: [(0, 1), (1, 2)]
In [178]: list(df["col1"])
Out[178]: [1, 2]
推荐阅读
- oauth-2.0 - oauth2 隐式流的理想过期时间是多少
- c++ - 在共享指针向量中按值擦除
- linux - 无法打开共享对象文件:没有这样的文件或目录 [在 VM 上安装 FSL]
- python - 在不获取的情况下获取 MySQL 游标行数
- python - 按不同范围的因素加权多列
- angular - Angular 6 错误处理 - 如何在模态中显示错误?
- actionscript-3 - 图像重叠 - 动作脚本 3 / adobe flash / adobe animate
- javascript - 无法在不刷新页面并重试 ES6 的情况下删除新创建的列表项
- java - 带有数组字符串主体的 JAVA 删除 API
- javascript - 如何在 Windows 10 上的电子应用程序中禁用键盘快捷键 Alt + Tab?