简体   繁体   中英

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. 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 .

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.).

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.

要添加到John Zwinck答案,只需将drivers.str [-3:]分配到新列。

df_results['new_column'] = drivers.str[-3:]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM