pandas 从熊猫数据框中的整列中删除某些字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51778480/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:55:05  来源:igfitidea点击:

Remove certain string from entire column in pandas dataframe

pythonstringpython-3.xpandasseries

提问by user3848207

I have a pandas dataframe dfwith the contents below:

我有一个df包含以下内容的Pandas数据框:

  Date          Factor       Expiry         Grade  
0 12/31/1991    2.138766     3/30/1992      -3.33% 
1 10/29/1992    2.031381     2/8/1993       -1.06% 
2 5/20/1993     2.075670     6/4/1993       -6.38% 

I would like the remove the %character from all the rows in the Gradecolumn. The result should look like this:

我想%从列中的所有行中删除字符Grade。结果应如下所示:

  Date          Factor     Expiry        Grade  
0 12/31/1991    2.138766   3/30/1992     -3.33 
1 10/29/1992    2.031381   2/8/1993      -1.06 
2 5/20/1993     2.075670   6/4/1993      -6.38 

I am using Python v3.6.

我正在使用 Python v3.6。

采纳答案by jpp

You can use string slicing and then convert to a numeric type via pd.to_numeric:

您可以使用字符串切片,然后通过pd.to_numeric以下方式转换为数字类型:

df['Grade'] = pd.to_numeric(df['Grade'].astype(str).str[:-1], errors='coerce')

Conversion to floatis recommended as a series of strings will be held in a generic and inefficient objectdtype, while numeric types permit vectorised operations.

float建议转换为,因为一系列字符串将保存在通用且低效的objectdtype 中,而数字类型允许向量化操作。

回答by Shaido - Reinstate Monica

Using str.replacewould work:

使用str.replace会起作用:

df['Grade'] = df['Grade'].str.replace('%', '')

回答by U10-Forward

Why not str.rstrip():

为什么不str.rstrip()

df['Grade'] = df['Grade'].str.rstrip('%')

回答by rafaelc

So long as we are giving alternatives, can also translate

只要我们给出替代方案,也可以 translate

df.Grade.str.translate(str.maketrans({'%':''})).astype(float)