首页 > 解决方案 > 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呢?两种对象类型与打印输出所指示的相同。

标签: pythonpandas

解决方案


他们在下面有不同的数据,这里看一下项目列表( .items 包括行):

In [177]: list(df.col1.items())                                                                                                                                                                
Out[177]: [(0, 1), (1, 2)]

In [178]: list(df["col1"])                                                                                                                                                                     
Out[178]: [1, 2]


推荐阅读