[英]Python and Pandas: How do I shorten string values from an individual column?
I'm a beginner to Python and Pandas, both, but I'm having a little trouble in something that I feel could be done pretty simply. 我都是Python和Pandas的初学者,但是我在一些可以简单完成的事情上遇到了一些麻烦。 I'm trying to shorten the string values of an individual column to just the abbreviations you see at the end. 我正在尝试将单个列的字符串值缩短为您最后看到的缩写。 Any help would be appreciated. 任何帮助,将不胜感激。 Thank you. 谢谢。
This is my current code below, just showing the list of drivers from the column Driver
. 这是我下面的当前代码,仅显示了Driver
列中的Driver
列表。
In[1]: drivers=df_results[0].loc[0:, 'Driver']
Out[1]:0 Sebastian Vettel VET
1 Lewis Hamilton HAM
2 Kimi Räikkönen RAI
3 Daniel Ricciardo RIC
As you can see, there are the names followed by the abbreviations, but I only want the abbreviations ( VET
, HAM
, etc.). 如您所见,名称后面紧跟着缩写,但是我只想要缩写( VET
, HAM
等)。
You can take the last three characters like this: 您可以这样输入最后三个字符:
drivers.str[-3:]
You could also use drivers.str.split()
and then take the last part. 您也可以使用drivers.str.split()
,然后进行最后一部分。
要添加到John Zwinck答案,只需将drivers.str [-3:]分配到新列。
df_results['new_column'] = drivers.str[-3:]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.