解析数字时,Pandas read_csv忽略美元符号

时间:2016-03-30 21:45:50

标签: python numpy pandas

我有一个csv文件,其中包含一些带有美元符号的单元格(例如<html> <head> <title>Betting Simulator Test!</title> </head> <body> <br/> <p id="p1">You have 500$</p> <br/> <form name="CoinFlip" action="" onsubmit="Create()" method="post"> Coins: <input type="text" name="Csubmit"> <input type="submit" value="Flip the Coin"> </form> <script type="text/javascript"> Balance = 500; function Game() { if(Balance >= 1) { var Coin = confirm("You have put " + sub + "$ in the CoinFlip!"); if(Coin == true) { var flip = true if(flip == true) { alert("You won " + sub + "$"); Balance = Balance + sub*2 - sub; Update = document.getElementById("p1").textContent="You have " + Balance + "$"; } else { alert("You lost " + sub + "$"); Balance = Balance - sub; Update = document.getElementById("p1").textContent="You have " + Balance + "$"; } } else { } } else { alert("You ran out of Money"); } } function Create() { sub = document.forms["CoinFlip"]["Csubmit"].value; if(sub <= Balance && sub > 0) { Game(); } else { alert("value does not make any sense!"); } } </script> </body> )。我强制函数$46.5中的所有类型都为numpy.float64。它抱怨pandas.read_csv()。有没有办法干净利落地处理这个问题?

1 个答案:

答案 0 :(得分:4)

您可以为相关列添加转换器:

pd.DataFrame({'col1': ['$46.51', '$38.00', 40], 
              'col2': [1, 2, 3]}).to_csv('test_df.csv', index=False)

>>> pd.read_csv('test_df.csv', converters={'col1': lambda s: float(s.replace('$', ''))})
    col1  col2
0  46.51     1
1  38.00     2
2  40.00     3