从 Pandas 系列的索引列表中删除字符串条目

Drop string entries from index list of Pandas series

我有一个以日期作为索引的系列,除了一些字符串值,即

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

我想删除这些字符串,但我还没有找到好的方法。将不胜感激。

您可以尝试将索引转换为日期时间索引,同时将不可转换的索引强制转换为 NaT。然后删除那些并再次索引:

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

得到

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