2017-08-13 116 views
0

我有以下df,其中df中的某些值是字符串(含有%)的字符串,而其他值不是。將字符串值的格式更改爲df中的數字

      test overall 
Quents Ratio   270.01% 256.02% 
Amount sulphur   0.17  0.19 
Amount salt     - 20.89 
amount silica    4.29% 6.84% 

我想使所有值的數字,因爲我想在2列進行一些分析。

所需的輸出:

      test overall 
Quents Ratio   270.01 256.02 
Amount sulphur   0.17  0.19 
Amount salt     - 20.89 
amount silica    4.29  6.84 

我曾嘗試是:

def numeric_df(df): 
    df_detail=df.loc[['Quents Ratio','amount silica'],:] 
    df_detail= df_detail.apply(lambda x:str(x)[:-1]) 
    return df 

但返回相同的初始DF。

我怎樣才能獲得所需的輸出?

+0

你需要將'-'替換爲'NaN'嗎? – jezrael

+0

不,我喜歡維護它 – ge00rge

+0

hmmm,但然後值不能是數字,因爲'-'是字符串。 – jezrael

回答

1

我想你需要replace,但價值也含有-,因此不可能轉換爲數值:

df = df.replace('%', '', regex=True) 

如果需要的所有值的數字和值只包含-字符:

df = df.replace({'%': '', '^-$':np.nan}, regex=True).astype(float) 
print (df) 
        test overall 
Quents Ratio 270.01 256.02 
Amount sulphur 0.17  0.19 
Amount salt  NaN 20.89 
amount silica  4.29  6.84 

另一種解決方案與to_numeric - 它將全部非數字替換爲NaN s:

df = df.replace('%', '', regex=True).apply(pd.to_numeric, errors='coerce') 
print (df) 
        test overall 
Quents Ratio 270.01 256.02 
Amount sulphur 0.17  0.19 
Amount salt  NaN 20.89 
amount silica  4.29  6.84 
相關問題