I am looking for an efficient way to remove specific elements from a column of data.
I have data like this:
year
1 (1991)
10 (1991-2001)
8 (1991-1998)
2 (2000-2002)
and I wanted to be like this:
year
1991
1991 - 2001
1991 - 1998
2000 - 2002
I want to remove the parentheses and elements before and after parentheses.
pandas.Series.str.extract
\((.*)\)
()
df = pd.DataFrame({'year': ['1 (1991)', '10 (1991-2001)', '8 (1991-1998)', '2 (2000-2002)']})
year
1 (1991)
10 (1991-2001)
8 (1991-1998)
2 (2000-2002)
df['year'] = df['year'].str.extract(r'\((.*)\)')
year
1991
1991-2001
1991-1998
2000-2002
You can use the below code
df['year'] = df['year'].str.split('(').str[1].str.strip(')')
output
year
0 1991
1 1991-2001
2 1991-1998
3 2000-2002
How about:
df['year'] = df['year'].str[1:-1]
Or safer if your data don't always start/end with '()'
:
# str.strip accepts regex
df['year'] = df['year'].str.strip('(|)')
Output:
1 1991
10 1991-2001
8 1991-1998
2 2000-2002
Name: year, dtype: object
lines = [
"year",
"1 (1991)",
"10 (1991-2001)",
"8 (1991-1998)",
"2 (2000-2002)"
]
formatted_lines = []
for line in lines:
updated_line = line.split('(') # Splits it into two lines: ["1 ", "1991)"]
updated_line = updated_line.replace(')') # remove extra parenthesis
formatted_lines.append(updated_line)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.