python how can i delete text after the second comma of a string?

Use mask with str.contains() to perform the operation on rows with the specified condition, and then use the following operation: .str.split(', ').str[0:2].agg(', '.join)):

df['Col'] = df['Col'].mask(df['Col'].str.contains('County, Texas'),
                           df['Col'].str.split(', ').str[0:2].agg(', '.join))

Full Code:

import pandas as pd
df = pd.DataFrame({'Col': {0: 'Jack Smith, Bank, Wilber, Lincoln County, Texas',
  1: 'Jack Smith, Union, Credit, Bank, Wilber, Lincoln County, Texas',
  2: 'Jack Smith, Union, Credit, Bank, Wilber, Lincoln County, Texas, Branch, Landing, Services',
  3: 'Jack Smith, Union, Credit, Bank, Wilber, Branch, Landing, Services'}})
df['Col'] = df['Col'].mask(df['Col'].str.contains('County, Texas'),
                           df['Col'].str.split(', ').str[0:2].agg(', '.join))                            
df
Out[1]: 
                                                 Col
0                                   Jack Smith, Bank
1                                  Jack Smith, Union
2                                  Jack Smith, Union
3  Jack Smith, Union, Credit, Bank, Wilber, Branc...

Per the updated question, you can use np.select:

import pandas as pd
df = pd.DataFrame({'Col': {0: 'Jack Smith, Bank, Wilber, Lincoln County, Texas',
  1: 'Jack Smith, Bank, Credit, Bank, Wilber, Lincoln County, Texas',
  2: 'Jack Smith, Bank, Union, Credit, Bank, Wilber, Lincoln County, Texas, Branch, Landing, Services',
  3: 'Jack Smith, Bank, Credit, Bank, Wilber, Branch, Landing, Services'}})
df['Col'] = np.select([df['Col'].str.contains('County, Texas') & ~df['Col'].str.contains('Union'),
                       df['Col'].str.contains('County, Texas') & df['Col'].str.contains('Union')],
                      [df['Col'].str.split(', ').str[0:2].agg(', '.join),
                       df['Col'].str.split(', ').str[0:3].agg(', '.join)],
                       df['Col'])                            
df
Out[2]: 
                                                 Col
0                                   Jack Smith, Bank
1                                   Jack Smith, Bank
2                            Jack Smith, Bank, Union
3  Jack Smith, Bank, Credit, Bank, Wilber, Branch...

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top