2017-06-17 81 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

相关问题