Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 拆下';S';从列表中单词的末尾(Python、Pandas)_Python 3.x_Pandas - Fatal编程技术网

Python 3.x 拆下';S';从列表中单词的末尾(Python、Pandas)

Python 3.x 拆下';S';从列表中单词的末尾(Python、Pandas),python-3.x,pandas,Python 3.x,Pandas,假设我有这样一个列表: Words One Twos Threes Four Fives ... Thousand 有没有一种相对简单的方法来删除单词末尾的“S”?因此,它将成为: Words One Two Three Four Five ... Thousand 您可以使用np。其中测试最后一个字符是否为“s”,如果是,则删除它,否则使用现有值,这将被矢量化,并且比列表理解快得多: In [14]: df['Words'] = np.where(df['Words'].str[-1]

假设我有这样一个列表:

Words
One
Twos
Threes
Four
Fives
...
Thousand
有没有一种相对简单的方法来删除单词末尾的“S”?因此,它将成为:

Words
One
Two
Three
Four
Five
...
Thousand

您可以使用
np。其中
测试最后一个字符是否为“s”,如果是,则删除它,否则使用现有值,这将被矢量化,并且比列表理解快得多:

In [14]:

df['Words'] = np.where(df['Words'].str[-1] == 's', df['Words'].str[:-1], df['Words'])
df
Out[14]:
      Words
0       One
1       Two
2     Three
3      Four
4      Five
5  Thousand
另一种可能更快的方法是使用
loc
,并且您的条件仅去除最后一个包含尾随s的字符,所有其他行保持不变:

In [18]:

df.loc[df['Words'].str[-1] == 's','Words'] = df['Words'].str[:-1]
df
Out[18]:
      Words
0       One
1       Two
2     Three
3      Four
4      Five
5  Thousand

让我们看看你到目前为止都做了些什么。很抱歉这个懒惰的问题!不幸的是,我现在在家,所以我将在明天的电脑前发布我尝试过的内容。请参见:您可以使用字符串[-1:]获取最后一个字符。做一些魔术,在结尾处用“s”对行进行排序谢谢,非常优雅快速跟进——如果我处理多单词字符串,这种方法仍然有效吗,例如:“Two和Threes”不,你必须使用正则表达式或lambda来测试每个字符的单词,然后去掉它——我很害怕——好吧,我看看我能做些什么!