Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove characters from pandas column

I'm trying to simply remove the '(' and ')' from the beginning and end of the pandas column series. This is my best guess so far but it just returns empty strings with () intact.

postings['location'].replace('[^\(.*\)?]','', regex=True)

The column looks like this: screenshot of jupyter notebook

like image 476
Keenan Burke-Pitts Avatar asked May 03 '17 18:05

Keenan Burke-Pitts


People also ask

How do I remove special characters from a DataFrame column in Python?

Add df = df. astype(float) after the replace and you've got it. I'd skip inplace and just do df = df. replace('\*', '', regex=True).

How do I remove a value from a column in pandas?

Use drop() method to delete rows based on column value in pandas DataFrame, as part of the data cleansing, you would be required to drop rows from the DataFrame when a column value matches with a static value or on another column value.

How do I remove part of a string in pandas?

Another option you have when it comes to removing unwanted parts from strings in pandas, is pandas. Series. str. extract() method that is used to extract capture groups in the regex pat as columns in a DataFrame.

How do I remove a specific character from a string in Python?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.


1 Answers

Working example

df = pd.DataFrame(dict(location=['(hello)']))

print(df)

  location
0  (hello)

@Psidom's Solution
str.strip

df.location.str.strip('()')

0    hello
Name: location, dtype: object

Option 2
str.extract

df.location.str.extract('\((.*)\)', expand=False)

0    hello
Name: location, dtype: object

Option 3
str.replace

df.location.str.replace('\(|\)', '')

0    hello
Name: location, dtype: object

Option 4
replace

df.location.replace('\(|\)', '', regex=True)

0    hello
Name: location, dtype: object
like image 170
piRSquared Avatar answered Oct 14 '22 21:10

piRSquared