Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从数据帧中的字符串中删除字符_Python_Regex_String_Python 3.x_Character - Fatal编程技术网

Python 从数据帧中的字符串中删除字符

Python 从数据帧中的字符串中删除字符,python,regex,string,python-3.x,character,Python,Regex,String,Python 3.x,Character,这里是python初学者。我想在某些条件下更改数据帧中列中的一些字符 此数据框看起来像: import pandas as pd import numpy as np raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'], 'age': [20, 19, 22, 21], 'favor

这里是python初学者。我想在某些条件下更改数据帧中列中的一些字符

此数据框看起来像:

import pandas as pd
import numpy as np
raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
                      'age': [20, 19, 22, 21],
                      'favorite_color': ['blue (VS)', 'red', 'yellow (AG)', "green"],
                      'grade': [88, 92, 95, 70]}
df = pd.DataFrame(raw_data, index = ['0', '1', '2', '3'])
df
我的目标是将“姓氏”列中的空格替换为括号和两个字母

蓝色而不是蓝色VS

我必须删除26个字母的变体,但只有一种格式:姓氏,后跟空格,后跟括号,后跟两个字母,后跟括号。 据我所知,在regexp中:

( \(..\)
我尝试使用str.replace,但它只适用于精确匹配,并替换整个值。 我也试过:

df.loc[df['favorite_color'].str.contains(‘VS’), 'favorite_color'] = ‘random’
它还替换整个值

我看到我只能重写该值,但我也看到使用该值:

df[0].str.slice(0, -5)
我可以删除包含搜索的字符串的最后5个字符

在我看来,我应该列出我想要删除的26个事件,并在保留之前的文本的同时,通过该列进行解析以删除这些事件。我找了一个和我的问题相似的帖子,但找不到解决办法。你知道方向吗?

你可以用str.replace替换为pattern\.*\

例:

输出:

您可以使用str.replace作为模式\.*\

例:

输出:


非常感谢你的工作,我没有遇到str.strip。我得多工作!非常感谢你的工作,我没有遇到str.strip。我得多工作!
import pandas as pd

raw_data = {'name': ['Willard Morris', 'Al Jennings', 'Omar Mullins', 'Spencer McDaniel'],
                      'age': [20, 19, 22, 21],
                      'favorite_color': ['blue (VS)', 'red', 'yellow (AG)', "green"],
                      'grade': [88, 92, 95, 70]}
df = pd.DataFrame(raw_data, index = ['0', '1', '2', '3'])
df["newCol"] = df["favorite_color"].str.replace("(\(.*?\))", "").str.strip()
print( df )
   age favorite_color  grade              name  newCol
0   20      blue (VS)     88    Willard Morris    blue
1   19            red     92       Al Jennings     red
2   22    yellow (AG)     95      Omar Mullins  yellow
3   21          green     70  Spencer McDaniel   green