2014-04-18 117 views
7

我對熊貓中的數據類型「對象」有點困惑。什麼是「對象」?在大熊貓中將浮點數轉換爲字符串

我想將變量「SpT」(見下文)從對象更改爲字符串。

> df_cleaned.dtypes 
    Vmag  float64 
    RA   float64 
    DE   float64 
    Plx   float64 
    pmRA  float64 
    pmDE  float64 
    B-V   float64 
    SpT   object 
    M_V   float64 
    distance float64 
    dtype: object 

爲此,我做了以下內容:

df_cleaned['SpT'] = df_cleaned['SpT'].astype(str) 

但是,對SPT的D型細胞沒有影響。

這樣做的原因是,當我做到以下幾點:

f = lambda s: (len(s) >= 2) and (s[0].isalpha()) and (s[1].isdigit()) 
i = df_cleaned['SpT'].apply(f) 
df_cleaned = df_cleaned[i] 

我得到:

TypeError: object of type 'float' has no len() 

因此,我相信,如果我轉換「對象」到「串」,我會得到做我想做的事。

更多信息:這是SPT的樣子:

HIP 
1    F5 
2    K3V 
3    B9 
4    F0V 
5    G8III 
6    M0V: 
7    G0 
8  M6e-M8.5e Tc 
9    G5 
10    F6V 
11    A2 
12   K4III 
13   K0III 
14    K0 
15    K2 
... 
118307 M2III: 
118308  K: 
118309  A2 
118310  K5 
118312  G5 
118313  F0 
118314  K0 
118315  K0III 
118316  F2 
118317  F8 
118318  K2 
118319  G2V 
118320  K0 
118321  G5V 
118322  B9IV 
Name: SpT, Length: 114472, dtype: object 
+0

'dtype'是非整數類型的一般numpy dtype,這表明您的列已經是一個字符串,當然是在轉換後,所以問題在於您的功能 – EdChum

+0

不能,該功能是正確的。下面的答案幫助了我。不過謝謝! – Rohit

+0

@aging_gorrila您使用的是什麼版本的熊貓? –

回答

11

如果列包含字符串或被視爲字符串,則其object一個dtype(但不一定是真的落後 - 詳見下文) 。下面是一個簡單的例子:

import pandas as pd 
df = pd.DataFrame({'SpT': ['string1', 'string2', 'string3'], 
        'num': ['0.1', '0.2', '0.3'], 
        'strange': ['0.1', '0.2', 0.3]}) 
print df.dtypes 
#SpT  object 
#num  object 
#strange object 
#dtype: object 

如果列只包含字符串,我們可以應用它len喜歡你做了什麼,應該很好地工作:

print df['num'].apply(lambda x: len(x)) 
#0 3 
#1 3 
#2 3 

然而,對象的dtype不確實的手段它只包含字符串。例如,列strange包含具有混合類型的對象 - 一些strfloat。應用功能len會提高類似於你已經看到了一個錯誤:

print df['strange'].apply(lambda x: len(x)) 
# TypeError: object of type 'float' has no len() 

因此,問題可能是你沒有正確地轉換列到字符串,並且列仍包含混合對象類型。

繼續上面的例子,讓我們轉換strange爲字符串,並檢查是否apply作品:

df['strange'] = df['strange'].astype(str) 
print df['strange'].apply(lambda x: len(x)) 
#0 3 
#1 3 
#2 3 

(有df_cleaned,並在你的問題df_clean有間可疑的差異,它是一個錯字或錯誤在導致問題的代碼?)

+0

感謝您澄清這一點。重點在於轉換命令「df_cleaned ['SpT'] = df_cleaned ['SpT']。astype(str)」沒有效果。我繼續得到同樣的錯誤。我如何確保所有的114000值已被轉換爲字符串?是的,有一個錯字。我糾正了它。 – Rohit

+0

我相信''df_cleaned ['SpT'] = df_cleaned ['SpT']。astype(str)''會正確完成轉換。你是否按照你的問題描述了確切的功能? –

+0

呃!我真的需要選擇更好的變量名稱!這些讓我感到困惑!是的,我正在申請一個錯誤的變量!謝謝...我需要咖啡! – Rohit

相關問題