2017-06-17 80 views
0

假設我們有熊貓:將所有列從字符串轉換爲數字,除了兩個?

>>> df.dtype Name object Height object Weight object Age object Job object

有沒有什麼簡單的方法來隱蔽,除了名稱的所有列和作業列與.to_numeric()方法?

我都試過,但它不工作

df.iloc[df.columns != Name & df.columns != Job] = pd.to_numeric(df.iloc[df.columns != Name & df.columns != Job], errors='coerce')

回答

0

這使我的腦海裏,使所有列的清單,除了姓名和工作,然後遍歷pandas.to_numeric在他們最簡單的方法:

cols=[i for i in df.columns if i not in ["Name","Job"]] 
for col in cols: 
    df[col]=pd.to_numeric(df[col]) 

編輯:

如果你絕對要使用數字而不是列名和已ķ現在在哪個指示他們是:

for i in [i for i in list(range(len(df.columns))) if i not in [0,4]]: 
    df.iloc[:,i]=pandas.to_numeric(df.iloc[:,i]) 

雖然這是比必要更復雜。

+0

謝謝你,就這麼簡單。但是如果我想使用索引,那我該怎麼寫呢? – Learner132

+0

「使用指數」是什麼意思?該操作在所有行上傳播,因此您無需打擾索引。 – baloo

+0

而不是在[cols = [i爲我在df.columns中如果我沒有在[「Name」,「Job」]]中使用[「Name」,「Job」]]'。有沒有可能像這樣使用列索引:[[df.loc [:0],df.loc [:,4]]' – Learner132

0

假設你有DF:

df 
Out[125]: 
    Name Height Weight Age Job 
0 0  2  3 4 5 

df.dtypes 
Out[126]: 

Name  object 
Height object 
Weight object 
Age  object 
Job  object 
dtype: object 

如果你必須使用pd.to_numeric那些列轉換,你可以這樣來做:

df2 = pd.concat([pd.DataFrame([pd.to_numeric(df[e],errors='coerce') \ 
           for e in df.columns if e not in ['Name','Job']]).T,\ 
       df[['Name','Job']]],axis=1) 


df2 
Out[138]: 
    Height Weight Age Name Job 
0  2  3 4 0 5 

df2.dtypes 
Out[139]: 
Height  int64 
Weight  int64 
Age  int64 
Name  object 
Job  object 
dtype: object 
+0

謝謝,是否可以使用索引?另外,如果我理解正確,還有其他方法可以做到嗎? – Learner132

相關問題