2

I have CSV data in the following format:

+-------------+-------------+-------+
|  Location   | Num of Reps | Sales |
+-------------+-------------+-------+
| 75894       |           3 |    12 |
| Burkbank    |           2 |    19 |
| 75286       |           7 |    24 |
| Carson City |           4 |    13 |
| 27659       |           3 |    17 |
+-------------+-------------+-------+

The Location column is of the object datatype. What I would like to do is to remove all rows that have non-numeric Location labels. So my desired output, given the above table would be:

+----------+-------------+-------+
| Location | Num of Reps | Sales |
+----------+-------------+-------+
|    75894 |           3 |    12 |
|    75286 |           7 |    24 |
|    27659 |           3 |    17 |
+----------+-------------+-------+

Now, I could hard code the solution in the following manner:

list1 = ['Carson City ', 'Burbank'];
df = df[~df['Location'].isin(['list1'])]

Which was inspired by the following post:

How to drop rows from pandas data frame that contains a particular string in a particular column?

However, what I am looking for is a general solution, that will work for any table of the type outlined above.

HMLDude
  • 1,407
  • 4
  • 25
  • 45

4 Answers4

5

Or you could do

df[df['Location'].str.isnumeric()]

  Location  Num of Reps  Sales
0    75894            3     12
2    75286            7     24
4    27659            3     17
Bharath
  • 28,527
  • 5
  • 52
  • 95
3

You can use pd.to_numeric to coerce non numeric values to nan and then filter based on if the Location is nan:

df[pd.to_numeric(df.Location, errors='coerce').notnull()]

#Location  Num of Reps  Sales
#0  75894            3     12
#2  75286            7     24
#4  27659            3     17
Psidom
  • 195,464
  • 25
  • 298
  • 322
1
In [139]: df[~df.Location.str.contains('\D')]
Out[139]:
  Location  Num of Reps  Sales
0    75894            3     12
2    75286            7     24
4    27659            3     17
MaxU - stop genocide of UA
  • 191,778
  • 30
  • 340
  • 375
0
df[df['Location'].str.isdigit()]


  Location  Num of Reps  Sales
0    75894            3     12
2    75286            7     24
4    27659            3     17
BENY
  • 296,997
  • 19
  • 147
  • 204