-2

Here's my problem: I have a column of numbers in pandas.dataFrame. But there are certain numbers that need to be converted because they might be string's.

Here's how the column currently looks:

[1
 -1,650.00
 -3
 ...]

I want it all to be integers. My code was:

df['columnname'].astype(int)

However, when I convert -1,650.00 to integer I'm getting an error. Even when the code is

df['columnname'].astype(float)
df['columnname'].astype(int)

It still doesn't solve the problem. It says could not convert string to float: - and the "-" is still not handled.

2 Answers2

1

Try this:

df['columnname'].replace(',','').astype(float) 

Or:

float(df['columnname'].replace(',',''))
Shapi
  • 5,493
  • 4
  • 28
  • 39
  • Thanks for your answer and edit! I appreciate your help. But my key problem is that the "-" is still there. The error says: "could not convert string to float: -". Do you know what I can do if I want to keep the "-" in this number? – Shaoqing Zhang Oct 23 '15 at 03:40
  • have you tryed `print type(float('-1650.00'.replace(',','')))` ? it returns ``. @ShaoqingZhang – Shapi Oct 23 '15 at 08:34
1

Float numbers use a dot to separate the integral part from the decimal part, not commas. Your vector should look something like this:

[1,
-1650.00,
-3,
]
Kira
  • 463
  • 4
  • 12