简体   繁体   English

Python和Pandas:如何从单个列中缩短字符串值?

[英]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.). 如您所见,名称后面紧跟着缩写,但是我只想要缩写( VETHAM等)。

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.

相关问题 如何从python中的excel列打印字符串值? - How do I print string values from excel column in python? Python:如何缩短熊猫列中的整数? - Python: how to shorten integers in a pandas column? Python/Pandas:如何根据个人 ID 替换 Pandas 数据框的特定值? - Python/Pandas: How do I replace specific values of a Pandas Data Frame based on individual id? 如何使用 Pandas 将逗号分隔的字符串列转换为单个因素? - How do I turn a comma separated string column to individual factors with Pandas? 如何逐个循环遍历 Pandas 列并检测另一列的更改? - How do I loop through Pandas column by individual and detect changes from another column? 如何从 Pandas Python 中 DataFrame 中的列中的字符串中提取一些值? - How to extract some values from string in column in DataFrame in Pandas Python? Python - 如何计算与字符串不匹配的 Pandas DataFrame 列中的值? - Python - How can I count the values from a Pandas DataFrame Column that doesn't match a string? 在 Pandas Python 中,如何替换字符串列中的字符? - In Pandas Python how do i replace Characters in String column? 如何在 Pandas 中将多列转换为单独的行/值? - How do I convert multiple columns to individual rows/values in pandas? 如何在python / pandas中将一个df列中的字符串添加到另一个? - How do I add a piece of string from one df column to another in python/pandas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM