pandas-如何将所有列从object转换为float类型

pandas-如何将所有列从object转换为float类型,pandas,type-conversion,Pandas,Type Conversion,我正在尝试将所有金额为“$”的列从object转换为float类型 使用下面的代码,我无法删除$符号 输入: df[:] = df[df.columns.map(lambda x: x.lstrip('$'))] 请使用以下基于正则表达式的匹配将所有出现的$替换为空字符 df = df.replace({'\$': ''}, regex=True) 更新:根据@Wen的建议,解决方案将是 df.iloc[:,9:32]=df.iloc[:,9:32].replace({'\$':''},r

我正在尝试将所有金额为“$”的列从object转换为float类型

使用下面的代码,我无法删除$符号

输入:

df[:] = df[df.columns.map(lambda x: x.lstrip('$'))]

请使用以下基于正则表达式的匹配将所有出现的$替换为空字符

df = df.replace({'\$': ''}, regex=True) 
更新:根据@Wen的建议,解决方案将是

df.iloc[:,9:32]=df.iloc[:,9:32].replace({'\$':''},regex=True).astype(float)

请使用以下基于正则表达式的匹配将所有出现的$替换为空字符

df = df.replace({'\$': ''}, regex=True) 
更新:根据@Wen的建议,解决方案将是

df.iloc[:,9:32]=df.iloc[:,9:32].replace({'\$':''},regex=True).astype(float)

您可以使用
提取

df=pd.DataFrame({'A':['$10.00','$10.00','$10.00']})
df.apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))
Out[333]: 
      A
0  10.0
1  10.0
2  10.0
更新

df.iloc[:,9:32]=df.iloc[:,9:32].apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))

您可以使用
提取

df=pd.DataFrame({'A':['$10.00','$10.00','$10.00']})
df.apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))
Out[333]: 
      A
0  10.0
1  10.0
2  10.0
更新

df.iloc[:,9:32]=df.iloc[:,9:32].apply(lambda x : x.str.extract('(\d+)',expand=False).astype(float))

您也可以尝试使用
applymap

df[:] = df.astype(str).applymap(lambda x:  x.lstrip('$')).astype(float)
如果
df
为:

   0   1   2
0  $1  7   5
1  $2  7   9
2  $3  7   9
然后,它将导致:

    0    1    2
0  1.0  7.0  5.0
1  2.0  7.0  9.0
2  3.0  7.0  9.0

您也可以尝试使用
applymap

df[:] = df.astype(str).applymap(lambda x:  x.lstrip('$')).astype(float)
如果
df
为:

   0   1   2
0  $1  7   5
1  $2  7   9
2  $3  7   9
然后,它将导致:

    0    1    2
0  1.0  7.0  5.0
1  2.0  7.0  9.0
2  3.0  7.0  9.0

还要添加astype(float)?还要添加astype(float)?如果我只想从第9列应用到第32列,我如何修改代码。如果我在df中有小数,比如['$10.40','$10.05','$10.80'],它会忽略小数后的数字。@prabhakar然后我们做df.iloc[:,9:32]=df.iloc[:,9:32]。替换({'$:'',regex=True)。astype(float)太好了,非常感谢。刚刚在replace中更正了您行中的小错误,df.iloc[:,9:32]=df.iloc[:,9:32].replace({'\$:'',regex=True)。astype(float)如果我只想从第9列应用到第32列,如何修改代码。如果df中有小数,比如['$10.40','$10.05','$10.80']它忽略小数点后的数字。@prabhakar然后我们执行df.iloc[:,9:32]=df.iloc[:,9:32]。替换({'$:'},regex=True)。aType(float)很好,谢谢。刚刚在replace中更正了行中的小错误,df.iloc[:,9:32]=df.iloc[:,9:32].replace({'\$:''},regex=True)。astype(float)