Drop string entries from index list of Pandas series

Viewed 28

I have a series which has dates as indices, except for some values that are strings, i.e.

2015-11-27 00:00:00                                   4
2016-08-03 00:00:00                                   1
Some string                                           1
2015-05-29 00:00:00                                   1
2015-05-20 00:00:00                                   2
2015-08-14 00:00:00                                   6

I want to drop those strings, but I haven't found a nice way to do that. Would appreciate any idea.

1 Answers

You can try converting your index to datetime index whilst coercing the un-convertibles to NaT. Then drop those and index again:

s.index = pd.to_datetime(s.index, errors="coerce")
s[s.index.dropna()]

to get

2015-11-27    4
2016-08-03    1
2015-05-29    1
2015-05-20    2
2015-08-14    6
Related