将对象类型的数据框列转换为浮点型

时间:2018-07-01 01:49:35

标签: python pandas machine-learning

我想将数据框的所有非浮点类型列都转换为浮点,有什么办法可以实现。如果我可以在One Go中完成,那将很棒。  下面是类型

longitude          -    float64 
latitude          -     float64
housing_median_age   -  float64
total_rooms          -  float64
total_bedrooms       -   object
population           -  float64
households            - float64
median_income         - float64
rooms_per_household   - float64
category_<1H OCEAN    -   uint8
category_INLAND        -  uint8
category_ISLAND        -  uint8
category_NEAR BAY     -   uint8
category_NEAR OCEAN    -  uint8

下面是我的代码段

import pandas as pd
import numpy as np 
from sklearn.model_selection import KFold

df = pd.DataFrame(housing)
df['ocean_proximity'] = pd.Categorical(df['ocean_proximity']) #type casting 
dfDummies = pd.get_dummies(df['ocean_proximity'], prefix = 'category' )
df = pd.concat([df, dfDummies], axis=1)
print df.head()
housingdata = df
hf = housingdata.drop(['median_house_value','ocean_proximity'], axis=1)
hl = housingdata[['median_house_value']]
hf.fillna(hf.mean,inplace = True)
hl.fillna(hf.mean,inplace = True)

2 个答案:

答案 0 :(得分:6)

如果您不需要对向下转换或错误处理进行特定控制,一种快速简便的方法是使用df = df.astype(float)

要获得更多控制,可以使用pd.DataFrame.select_dtypes按dtype选择列。然后在列的子集上使用pd.to_numeric

设置

df = pd.DataFrame([['656', 341.341, 4535],
                   ['545', 4325.132, 562]],
                  columns=['col1', 'col2', 'col3'])

print(df.dtypes)

col1     object
col2    float64
col3      int64
dtype: object

解决方案

cols = df.select_dtypes(exclude=['float']).columns

df[cols] = df[cols].apply(pd.to_numeric, downcast='float', errors='coerce')

结果

print(df.dtypes)

col1    float32
col2    float64
col3    float32
dtype: object

print(df)

    col1      col2    col3
0  656.0   341.341  4535.0
1  545.0  4325.132   562.0

答案 1 :(得分:0)

枚举转换为数字并插入到新的数据框

New_DataFrame = pd.DataFrame()
x = {New_DataFrame.insert(i, name, pd.to_numeric(df[name], errors = "coerce"), True) if(df[name].dtype.name=='object') else New_DataFrame.insert(i, name, df[name], True) for i, name in enumerate(df.columns)}
print(New_DataFrame.head())`