python - 将 numpy 数组更改为 float

标签 python numpy pandas

我有一个对象类型的 numpy 数组。我想找到具有数值的列并将它们转换为 float 。我还想找到具有对象值的列的索引。 这是我的尝试:

import numpy as np
import pandas as pd

df = pd.DataFrame({'A' : [1,2,3,4,5],'B' : ['A', 'A', 'C', 'D','B']})
X = df.values.copy()
obj_ind = []
for ind in range(X.shape[1]):
    try:
        X[:,ind] = X[:,ind].astype(np.float32)
    except:
        obj_ind = np.append(obj_ind,ind)

print obj_ind

print X.dtype

这是我得到的输出:

[ 1.]
object

最佳答案

通常,您尝试将 astype 应用于每一列的想法很好。

In [590]: X[:,0].astype(int)
Out[590]: array([1, 2, 3, 4, 5])

但是您必须将结果收集在一个单独的列表中。您不能只是将它们放回 X 中。然后可以连接该列表。

In [601]: numlist=[]; obj_ind=[]

In [602]: for ind in range(X.shape[1]):
   .....:     try:
   .....:         x = X[:,ind].astype(np.float32)
   .....:         numlist.append(x)
   .....:     except:
   .....:         obj_ind.append(ind)

In [603]: numlist
Out[603]: [array([ 3.,  4.,  5.,  6.,  7.], dtype=float32)]

In [604]: np.column_stack(numlist)
Out[604]: 
array([[ 3.],
       [ 4.],
       [ 5.],
       [ 6.],
       [ 7.]], dtype=float32)

In [606]: obj_ind
Out[606]: [1]

X 是一个 dtype object 的 numpy 数组:

In [582]: X
Out[582]: 
array([[1, 'A'],
       [2, 'A'],
       [3, 'C'],
       [4, 'D'],
       [5, 'B']], dtype=object)

您可以使用相同的转换逻辑来创建混合了 int 和对象字段的结构化数组。

In [616]: ytype=[]

In [617]: for ind in range(X.shape[1]):
    try:                        
        x = X[:,ind].astype(np.float32)
        ytype.append('i4')
    except:
        ytype.append('O')       

In [618]: ytype
Out[618]: ['i4', 'O']

In [620]: Y=np.zeros(X.shape[0],dtype=','.join(ytype))

In [621]: for i in range(X.shape[1]):
    Y[Y.dtype.names[i]] = X[:,i]

In [622]: Y
Out[622]: 
array([(3, 'A'), (4, 'A'), (5, 'C'), (6, 'D'), (7, 'B')], 
      dtype=[('f0', '<i4'), ('f1', 'O')])

Y['f0'] 给出数字字段。

关于python - 将 numpy 数组更改为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32207474/

相关文章:

python - 将一种查询格式解析为另一种格式

python - 为什么 Python 会删除字符串的最后一个字符?

python - Django UserCreationForm 自定义字段

python - 如何使用置换数组有效地置换稀疏(Numpy)矩阵中的行?

python - 为什么 pd.to_numeric 不适用于大数字?

numpy:在大端写入 uint16 的大型二维数组

python - 如何过滤具有列表的列的数据框包含值

python - 将尾随字符替换为另一个字符

python - Pandas : transform a 2D dataframe to a 3D one

python - Pandas 选择聚合后要保存的列