python - 将 panda 对象转换为 numpy 数组

标签 python numpy pandas import

我有一个简单的代码来查找数据集中的相似行。

 h=0
count=0
#227690
deletedIndexes=np.zeros((143,))
len(data)
for i in np.arange(len(data)):
    if(data[i-1,2]==data[i,2]):
        similarIndexes[h]=int(i)
        h=h+1        
        count=count+1
        print("similar found in -->", i," there are--->", count)

当数据是 numpy.ndarray 时它可以正常工作但是如果数据是 panda 对象,我会给出以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
 File "<stdin>", line 7, in smilarData
  File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1658, in __getitem__
return self._getitem_column(key)
  File "/usr/lib/python2.7/dist-packages/pandas/core/frame.py", line 1665, in _getitem_column

返回 self._get_item_cache(key)

File "/usr/lib/python2.7/dist-packages/pandas/core/generic.py", line 1005, in _get_item_cache
values = self._data.get(item)



File "/usr/lib/python2.7/dist-packages/pandas/core/internals.py", line 2874, in get
_, block = self._find_block(item)



File "/usr/lib/python2.7/dist-packages/pandas/core/internals.py", line 3186, in _find_block
self._check_have(item)



 File "/usr/lib/python2.7/dist-packages/pandas/core/internals.py", line 3193, in _check_have


 raise KeyError('no item named %s' % com.pprint_thing(item))
KeyError: u'no item named (-1, 2)'

我应该怎么做才能使用这个代码?如果将 pandas 对象转换为 numpy 数组有帮助,我该怎么做?

最佳答案

我还无法对艾德丽安的回答发表评论,所以我想补充一点,数据帧已经内置了将 df 转换为数组(即矩阵)的方法

>>> df = pd.DataFrame({"a":range(5),"b":range(5,10)})
>>> df
   a  b
0  0  5
1  1  6
2  2  7
3  3  8
4  4  9
>>> mat = df.as_matrix()
array([[0, 5],
       [1, 6],
       [2, 7],
       [3, 8],
       [4, 9]])
>>>col = [x[0] for x in mat] # to get certain columns
>>> col
[0, 1, 2, 3, 4]

还可以查找重复的行:

>>> df2
   a  b
0  0  5
1  1  6
2  2  7
3  3  8
4  4  9
5  0  5
>>> df2[df2.duplicated()]
   a  b
5  0  5

关于python - 将 panda 对象转换为 numpy 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33314109/

相关文章:

Python 导入语句语义

python - Linux epoll 系统调用,等待数据可用

python - 有效地找到数组中 DataFrame 值的索引

python - numpy.ufunc 大小错误,尝试重新编译。即使使用最新的 pandas 和 numpy 版本

python - 如何根据连续索引拆分 DataFrame?

Python 获取特定角色的所有成员列表

python - Numpy:具有不同值的索引样本组

python Pandas : transforming - moving values from diagonal

python - 分组并返回所有列

python - 将列表转换为对角矩阵 DataFrame