簡體   English   中英

將pandas dataframe中的列從String轉換為Float

[英]Convert a column in pandas dataframe from String to Float

我已經閱讀了各種解決方案,並嘗試了此處所述的解決方案: Pandas:轉換為數字,必要時創建NaN

但它並沒有真正解決我的問題:我有一個數據['PricePerSeat_Outdoor']包含多個列,其中列['PricePerSeat_Outdoor']包含一些浮點值,一些空值和一些'-'

    print type(df_raw['PricePerSeat_Outdoor'][99])
    print df_raw['PricePerSeat_Outdoor'][95:101]
    df_raw['PricePerSeat_Outdoor'] = df_raw['PricePerSeat_Outdoor'].apply(pd.to_numeric, errors='coerce')
    print type(df_raw['PricePerSeat_Outdoor'][99]) 

然后我得到了:

<type 'str'>
95     17.21
96     17.24
97         -
98         -
99      17.2
100    17.24
Name: PricePerSeat_Outdoor, dtype: object
<type 'str'>

第98行和第99行的值未轉換。 同樣,我已經嘗試過多種方法,包括以下但是它沒有用。 非常感謝,如果有人能給我一些提示。

df_raw['PricePerSeat_Outdoor'] = df_raw['PricePerSeat_Outdoor'].apply(pd.to_numeric, errors='coerce')

另外,如何將多個列一次轉換為數字? 謝謝。

嘗試這個:

df_raw['PricePerSeat_Outdoor'] = pd.to_numeric(df_raw['PricePerSeat_Outdoor'], errors='coerce')

這是一個例子:

In [97]: a = pd.Series(['17.21','17.34','15.23','-','-','','12.34']

In [98]: b = pd.Series(['0.21','0.34','0.23','-','','-','0.34'])

In [99]: df = pd.DataFrame({'a':a, 'b':b})

In [100]: df['c'] = np.random.choice(['a','b','b'], len(df))

In [101]: df
Out[101]:
       a     b  c
0  17.21  0.21  a
1  17.34  0.34  b
2  15.23  0.23  b
3      -     -  b
4      -        b
5            -  b
6  12.34  0.34  b

In [102]: cols_to_convert = ['a','b']

In [103]: cols_to_convert
Out[103]: ['a', 'b']

In [104]: for col in cols_to_convert:
   .....:         df[col] = pd.to_numeric(df[col], errors='coerce')
   .....:

In [105]: df
Out[105]:
       a     b  c
0  17.21  0.21  a
1  17.34  0.34  b
2  15.23  0.23  b
3    NaN   NaN  b
4    NaN   NaN  b
5    NaN   NaN  b
6  12.34  0.34  b

校驗:

In [106]: df.dtypes
Out[106]:
a    float64
b    float64
c     object
dtype: object

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM