[英]changing numpy array to float
我有一個類型對象的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
通常,您嘗試將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和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']
給出數字字段。
df.dtypes
返回一個熊貓系列,可以進一步操作
# 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
我認為這可能會有所幫助
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
執行相同的操作要慢得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.