【问题标题】:changing numpy array to float将 numpy 数组更改为浮点数
【发布时间】:2015-11-19 08:42:05
【问题描述】:

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

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

【问题讨论】:

  • 不清楚您在这里期待什么,您的输出显示第二列无法转换为浮点数并且 dtype 是 object 这是正确的,因为这是 str dtype,如果您想要列名,则返回 obj_ind = np.append(obj_ind,x.columns[ind])
  • 我想将我的第一列转换为 float @EdChum
  • numpy 数组的元素不能有不同的dtypes。您可能需要一个结构化数组来代替
  • 这能回答你的问题吗? Converting numpy dtypes to native python types

标签: python numpy pandas


【解决方案1】:

df.dtypes返回一个可以进一步操作的pandas系列

# find columns of type int
mask = df.dtypes==int
# select columns for for the same
cols = df.dtypes[mask].index
# select these columns and convert to float
new_cols_df = df[cols].apply(lambda x: x.astype(float), axis=1)
# Replace these columns in original df
df[new_cols_df.columns] = new_cols_df

【讨论】:

  • 我发布的是一个最小的工作示例。在我的完整代码中,我将无法访问 df。仅限于 X。@shanmuga
【解决方案2】:

通常,您尝试将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 是一个 numpy 数组,dtype 为object

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

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

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'] 给出数字字段。

【讨论】:

    【解决方案3】:

    我认为这可能会有所帮助

    def func(x):
      a = None
      try:
        a = x.astype(float)
      except:
        # x.name represents the current index value 
        # which is column name in this case
        obj.append(x.name) 
        a = x
      return a
    
    obj = []
    new_df = df.apply(func, axis=0)
    

    这将保留object 列,供您以后使用。

    注意:在使用pandas.DataFrame 时避免使用循环使用迭代,因为这比使用apply 执行相同操作要慢得多。

    【讨论】:

      猜你喜欢
      • 2014-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-14
      • 1970-01-01
      相关资源
      最近更新 更多