如何在pandas数据框中删除字符串的部分?

huangapple go评论85阅读模式
英文:

How to remove section of string in pandas dataframe?

问题

以下是翻译好的部分:

要做的是在数据框列中删除字符串中'of'之前的所有文本。例如:

ColA          ColB 
 1       '12 miles ESE of Jackson,MS'
 2       '8 miles NE of New York, NY'
 3       '223 miles SW of Atlanta, GA'

我想要的是这样的结果:

ColA           ColB 
 1           'Jackson,MS'
 2           'New York,NY'
 3           'Atlanta,GA'

谢谢!

英文:

What I am looking to do is remove all text before the work 'of' in a string in a dataframe column. For example:

ColA          ColB 
 1       '12 miles ESE of Jackson,MS'
 2       '8 miles NE of New York, NY'
 3       '223 miles SW of Atlanta, GA'

What I am looking to get is this:

ColA           ColB 
 1           'Jackson,MS'
 2           'New York,NY'
 3           'Atlanta,GA'

Thank you!

答案1

得分: 3

你可以执行:

df['ColB'] = df['ColB'].str.split('of').str[1]
英文:

You can do:

df['ColB'] = df['ColB'].str.split('of').str[1]

答案2

得分: 2

"'" + df['ColB'].str.extract("of\s(.*$)") 输出:

0 'Jackson,MS'
1 'New York, NY'
2 'Atlanta, GA'

英文:

Try, using regex and .str.extract:

"'" + df['ColB'].str.extract("of\s(.*$)")

Output:

                0
0    'Jackson,MS'
1  'New York, NY'
2   'Atlanta, GA'

答案3

得分: 1

使用 .replace 方法:

df.ColB = df.ColB.replace(r'.*of (.*?)', '\\1', regex=True)

然后你的 ColB 列将会是:

    ColB
0  Jackson,MS
1  New York, NY
2  Atlanta, GA
英文:

Use .replace:

df.ColB = df.ColB.replace(r'.*of (.*)', '\', regex=True)

then your ColB will be

	ColB
0 	Jackson,MS
1 	New York, NY
2 	Atlanta, GA

huangapple
  • 本文由 发表于 2020年1月6日 21:40:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613160.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定