从 pandas 系列中删除索引以特定单词开头的元素
Drop elements from pandas series having index starting with a particular word
我有一个pandas系列,如下图
vol = pd.Series([1,0,-3,2,5],index=['Jan, 15','Oct, 17','Apr, 18','Sep, 19', 'Jan, 18'])
print(vol)
Jan, 15 1
Oct, 17 0
Apr, 18 -3
Sep, 19 2
Jan, 18 5
dtype: int64
如果我需要删除一个已知 index
的元素,我可以使用 .drop()
函数,但在这里我必须知道 index
。如何检测索引以 Jan
开头的元素?我想要以下 -
print(vol)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
函数 .filter()
已关闭,例如 -
print(vol.filter(like='Jan'))
Jan, 15 1
Jan, 18 5
dtype: int64
但是,vol.filter(like != 'Jan')
不起作用。
使用 boolean indexing
with Series.str.startswith
并通过 ~
:
反转掩码
s = vol[~vol.index.str.startswith('Jan')]
print (s)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
对于索引中的检查值(不仅是起始位置)使用Series.str.contains
:
s = vol[~vol.index.str.contains('Jan')]
print (s)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
替代 filter
:
s = vol.filter(regex=r'^(?!.*Jan).*$')
print (s)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
你已经提到了所有的部分,你可以这样做:
vol.drop(vol.filter(like='Jan').index)
我有一个pandas系列,如下图
vol = pd.Series([1,0,-3,2,5],index=['Jan, 15','Oct, 17','Apr, 18','Sep, 19', 'Jan, 18'])
print(vol)
Jan, 15 1
Oct, 17 0
Apr, 18 -3
Sep, 19 2
Jan, 18 5
dtype: int64
如果我需要删除一个已知 index
的元素,我可以使用 .drop()
函数,但在这里我必须知道 index
。如何检测索引以 Jan
开头的元素?我想要以下 -
print(vol)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
函数 .filter()
已关闭,例如 -
print(vol.filter(like='Jan'))
Jan, 15 1
Jan, 18 5
dtype: int64
但是,vol.filter(like != 'Jan')
不起作用。
使用 boolean indexing
with Series.str.startswith
并通过 ~
:
s = vol[~vol.index.str.startswith('Jan')]
print (s)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
对于索引中的检查值(不仅是起始位置)使用Series.str.contains
:
s = vol[~vol.index.str.contains('Jan')]
print (s)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
替代 filter
:
s = vol.filter(regex=r'^(?!.*Jan).*$')
print (s)
Oct, 17 0
Apr, 18 -3
Sep, 19 2
dtype: int64
你已经提到了所有的部分,你可以这样做:
vol.drop(vol.filter(like='Jan').index)