从索引以特定单词开头的系列中删除元素

2024-04-24 22:18:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫系列,如下所示

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的元素,我可以使用^{}函数,但这里我必须知道index。如何确定索引以Jan开头的元素?我想要以下-

print(vol)
    Oct, 17    0
    Apr, 18   -3
    Sep, 19    2
    dtype: int64

函数^{}很接近,例如-

print(vol.filter(like='Jan'))
    Jan, 15    1
    Jan, 18    5
    dtype: int64

但是,vol.filter(like != 'Jan')不起作用


Tags: 函数元素indexfilteroctaprsepjan
2条回答

你已经提到了所有的部分,你可以做:

vol.drop(vol.filter(like='Jan').index)

^{}^{}一起使用,并通过~反转掩码:

s = vol[~vol.index.str.startswith('Jan')]
print (s)
Oct, 17    0
Apr, 18   -3
Sep, 19    2
dtype: int64

对于索引中的检查值(不仅仅是起始位置),请使用^{}

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

相关问题 更多 >