Stripping DataFrame column from text to make integer

Viewed 136

I couldn't find an easy way to do this and none of the complex ways worked. Can you help?

I have a dataframe resulting from a web-scrape. In there I have a data['Milage'] column that has the following result: '80,000 miles'. Obviously that's a string, so I'm looking for a way to erase all content that isnt numeric and convert that string to straigt numbers '80,000 miles' -> '80000'

I tried the following:

data['Milage'] = data['Milage'].str[1:].astype(int)

No idea what the code above does, I took it from another post from here. But I get the following error message:

  File "autotrader.py", line 73, in <module>
    data['Milage'] = data['Milage'].str[1:].astype(int)
AttributeError: 'str' object has no attribute 'str'

The other solution I tried was this:

data['Milage'] = str(data['Milage']).extract('(\d+)').astype(int)

And the resulting error is as follows:

  File "autotrader.py", line 73, in <module>
    data['Milage'] = str(data['Milage']).extract('(\d+)').astype(int)
AttributeError: 'str' object has no attribute 'extract'

I would appreciate any help! Thank you

1 Answers

After some test problem was data is dictionary, you need processing df for DataFrame.

I think you need remove non numeric values and convert to integers:

df['Milage'] = df['Milage'].str.replace('\D','').astype(int)
print(df['Milage'])
0      70000
1      69186
2      46820
3      54000
4      83600
5     139000
6      62000
7      51910
8      86000
9      38000
10     65000
11    119000
12     49500
13     60000
14     35000
15     57187
16     45050
17     80000
18     84330
19     85853
Name: Milage, dtype: int32
Related