我有这个使用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'
只想更改列的格式以应用上述操作。
答案 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()])