gpt4 book ai didi

Python 3 - Zip 是 pandas 数据框中的迭代器

转载 作者:IT老高 更新时间:2023-10-28 20:46:37 26 4
gpt4 key购买 nike

我正在关注 Pandas tutorials

教程是使用 python 2.7 编写的,我是在 python 3.4 中编写的

这是我的版本详情。

In [11]: print('Python version ' + sys.version)
Python version 3.4.1 |Anaconda 2.0.1 (64-bit)| (default, Jun 11 2014, 17:27:11)
[MSC v.1600 64 bit (AMD64)]

In [12]: print('Pandas version ' + pd.__version__)
Pandas version 0.14.1

我按照教程创建 zip

In [13]: names = ['Bob','Jessica','Mary','John','Mel']

In [14]: births = [968, 155, 77, 578, 973]

In [15]: zip?
Type: type
String form: <class 'zip'>
Namespace: Python builtin
Init definition: zip(self, *args, **kwargs)
Docstring:
zip(iter1 [,iter2 [...]]) --> zip object

Return a zip object whose .__next__() method returns a tuple where
the i-th element comes from the i-th iterable argument. The .__next__()
method continues until the shortest iterable in the argument sequence
is exhausted and then it raises StopIteration.

In [16]: BabyDataSet = zip(names,births)

但创建后第一个错误显示我看不到 zip 的内容。

In [17]: BabyDataSet
Out[17]: <zip at 0x4f28848>

In [18]: print(BabyDataSet)
<zip object at 0x0000000004F28848>

然后当我去创建数据框时,我得到了这个迭代器错误。

In [21]: df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-21-636a49c94b6e> in <module>()
----> 1 df = pd.DataFrame(data = BabyDataSet, columns=['Names', 'Births'])

c:\Users\Sayth\Anaconda3\lib\site-packages\pandas\core\frame.py in __init__(self
, data, index, columns, dtype, copy)
255 copy=copy)
256 elif isinstance(data, collections.Iterator):
--> 257 raise TypeError("data argument can't be an iterator")
258 else:
259 try:

TypeError: data argument can't be an iterator

In [22]:

这是 python 3 的陷阱,我需要以不同的方式做吗?还是其他?

最佳答案

你需要改变这一行:

BabyDataSet = zip(names,births)

到:

BabyDataSet = list(zip(names,births))

这是因为 zip 现在在 python 3 中返回一个迭代器,因此您的错误消息。更多详情见:http://www.diveintopython3.net/porting-code-to-python-3-with-2to3.html#ziphttps://docs.python.org/3/library/functions.html#zip

关于Python 3 - Zip 是 pandas 数据框中的迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26121009/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com