如果您能帮助我解决您刚才在下面的链接中提供的解决方案,我将不胜感激: Converting a list of ints, tuples into an numpy array
您可能还记得,您解释了一种将元组转换为 numpy 数组的方法。 我正在从事一个数据挖掘性质的项目,我发现最快的方法 收集数据是通过使用元组,但除了记录输入之外,我还需要一个 numpy 数组。所以我查找了您的解决方案并且有点奏效 - 问题出在数据类型上。 我有一个看起来像这样的元组:
t1=[[datetime.datetime(2013, 10, 1, 20, 54, 51), 'last'],[datetime.datetime(2013, 8, 1, 20, 54, 51), 'First'],[datetime.datetime(2013, 9, 2, 20, 54, 51), 'second']]
当我尝试像这样修改你的代码时
A = np.array([tuple(i) for i in t1],dtype=[('ReportTime',datetime.datetime.__class__),('activity',str.__class__)])
numpy 无法识别数据类型。 我输入了错误的数据类型吗? 谢谢你的时间
最佳答案
由于您从事的是数据挖掘性质的项目,您是否考虑过使用 Pandas?
这是一个示例,说明如何将元组列表转换为 Pandas 数据框。我强调了我第一次开始使用 Pandas 时犯的一些新手常见错误,让您了解可以做什么和不能做什么。
In [1]: import pandas as pd
In [2]: data = [(1, 2), (1, 5), (2, 3), (2, 2)]
In [3]: pd.datafr
In [3]: pd.DataFrame(data)
Out[3]:
0 1
0 1 2
1 1 5
2 2 3
3 2 2
In [4]: pd.columns[0] = 'column 1'
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-c313e6b0cb87> in <module>()
----> 1 pd.columns[0] = 'column 1'
AttributeError: 'module' object has no attribute 'columns'
In [5]: df = pd.DataFrame(data)
In [6]: df
Out[6]:
0 1
0 1 2
1 1 5
2 2 3
3 2 2
In [7]: df.columns
Out[7]: Int64Index([0, 1], dtype=int64)
In [8]: df.columns[1] = "column 2"
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-8-76ee806aec72> in <module>()
----> 1 df.columns[1] = "column 2"
/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pandas-0.12.0-py2.7-macosx-10.6-intel.egg/pandas/core/index.pyc in __setitem__(self, key, value)
328
329 def __setitem__(self, key, value):
--> 330 raise Exception(str(self.__class__) + ' object is immutable')
331
332 def __getitem__(self, key):
Exception: <class 'pandas.core.index.Int64Index'> object is immutable
In [9]: df.columns = ["column 1", "column 2"]
In [10]: df
Out[10]:
column 1 column 2
0 1 2
1 1 5
2 2 3
3 2 2
In [11]: exit()
特别是你的例子:
In [1]: import pandas as pd
In [3]: import datetime
In [4]: t1=[[datetime.datetime(2013, 10, 1, 20, 54, 51), 'last'],[datetime.datetime(2013, 8, 1, 20, 54, 51), 'First'],[datetime.datetime(2013, 9, 2, 20, 54, 51), 'second']]
In [5]: t1
Out[5]:
[[datetime.datetime(2013, 10, 1, 20, 54, 51), 'last'],
[datetime.datetime(2013, 8, 1, 20, 54, 51), 'First'],
[datetime.datetime(2013, 9, 2, 20, 54, 51), 'second']]
In [6]: df = pd.DataFrame(t1)
In [7]: df
Out[7]:
0 1
0 2013-10-01 20:54:51 last
1 2013-08-01 20:54:51 First
2 2013-09-02 20:54:51 second
关于python - numpy 无法识别转换中的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20846826/