0

I want to convert a str number into a float or int numerical type. However, it is throwing an error that it can't, so I am removing the comma. The comma will not be removed, so I need to find a way of finding a way of designating the location in the number space like say fourth.

power4 = power[power.get('Number of Customers Affected') != 'Unknown']
power5 = power4[pd.notnull(power4['Number of Customers Affected'])]
power6 = power5[power5.get('NERC Region') == 'RFC']
power7 = power6.get('Number of Customers Affected').loc[1]
power8 = power7.strip(",")
power9 = float(power8)


ValueError                                Traceback (most recent call last) <ipython-input-70- 32ca4deb9734> in <module>
      6 power7 = power6.get('Number of Customers Affected').loc[1]
      7 power8 = power7.strip(",")
----> 8 power9 = float(power8)
      9 
     10 

ValueError: could not convert string to float: '127,000'
John
  • 53
  • 2
  • 7

3 Answers3

2

Use replace()

float('127,000'.replace(',',''))
0

Have you tried pandas.to_numeric?

import pandas as pd

a = '1234'
type(a)

a = pd.to_numeric(a)
type(a)
Shababb Karim
  • 3,614
  • 1
  • 22
  • 35
Dean
  • 151
  • 1
  • 1
  • 10
0

In the

power8 = power7.strip(",")

line, do

power8 = power7.replace(',', '')

strip() will not work here. What is required is replace() method of string. You may also try

''.join(e for e in s if e.isdigit())

Or,

s = ''.join(s.split(','))

RegeEx can also be a way to solve this, or you can have a look at this answer : https://stackoverflow.com/a/266162/9851541

Swati Srivastava
  • 1,102
  • 1
  • 12
  • 18