Remove all after specific characters in a dataframe Using Python

Viewed 80

Having a list of specific characters, We need to remove all the characters after it.

Input Data:

  text_dir
abc School, Uk
xyz College, USA
Pqr University, Berlin

Output Values needed:

  text_dir
abc School
xyz College
Pqr University

Code snippet:

spl_character=['School', 'college', 'university']
df['text_dir'] = df['text_dir'].str.split(spl_character).str[0]

Gives Error:
TypeError: unhashable type: 'list'
3 Answers

IIUC:

pat = f'(?i)^(.*)({"|".join(spl_character)}).*$'
df.text_dir.str.replace(pat, r'\1\2', regex=True)

0        abc School
1       xyz College
2    Pqr University
Name: text_dir, dtype: object

I modified your inputs and try to solve this problem, I have used regular expressions for this problem.

import pandas as pd
import re


text_dir = ["abc School, Uk", "xyz College, USA", "Pqr University, Berlin"]
spl_character=['School,', 'College,', 'University,']


df = pd.DataFrame()
df['text_dir'] = text_dir


final_list = []

for item in df.text_dir:
    for character in spl_character:
        if j in i.split(' '):
            val_re = re.compile("^(.*)"+character+"")
            val_match = val_re.search(item)
            final_list.append(val_match.group())

df['text_dir'] = final_list

Output:

    text_dir
0   abc School,
1   xyz College,
2   Pqr University,
import pandas as pd

text_dir = ["abc School, Uk", "xyz College, USA", "Pqr University, Berlin"]
df = pd.DataFrame()
df['text_dir'] = text_dir
      text_dir
0   abc School, Uk
1   xyz College, USA
2   Pqr University, Berlin

Using lambda function

# Reformat values for column "text_dir" using a lambda function
df['text_dir'] = df['text_dir'].apply(lambda x: x.split(',')[0])

Output

    text_dir
0   abc School
1   xyz College
2   Pqr University
Related