非常努力将数据帧的格式从字符串转换为浮点数

时间:2017-05-21 14:55:50

标签: pandas

我有这个使用read_html属性获得的df:

              0      1         2        3 

1             AB   16.38   16197.69  19/05
2             AC   81.48    4671.23  19/05
3             AR   12.10    3329.37  19/05
4             AS   35.69   11178.46  19/05

第二列和第三列是数字,但它们被记录为str。

我想将它们变成浮点数,因为在第三列中,我想对列2的每个值进行除以它的总和。

所需的输出将是这样的:

     0          1         2       3 

1   AB      16.38    0.457    19/05
2   AC      81.48    0.132    19/05
3   AR      12.10    0.094    19/05
4   AS      35.69    0.315    19/05

这就是我的尝试:

一方面说明小数和数千

pd.read_html('http:// whatever', flavor='html5lib', thousands='.',decimal=',')

另一方面将df的格式更改为numeric

df.apply(pd.to_numeric, errors='ignore')

当我在列上打印所需的公式时:

df.loc[:,2]/df.loc[:,2].sum())

出现以下错误:

unsupported operand type(s) for /: 'str' and 'str'

只想更改列的格式以应用上述操作。

1 个答案:

答案 0 :(得分:1)

我认为您需要to_numeric才能将非数字转换为NaN

df[1] = pd.to_numeric(df[1], errors='coerce')
df[2] = pd.to_numeric(df[2], errors='coerce')

但首先你可以检查哪些值没有被解析:

print (df[pd.to_numeric(df[1], errors='coerce').isnull()])

print (df[pd.to_numeric(df[2], errors='coerce').isnull()])