KReEd
KReEd

Reputation: 368

Delete rows if found string or special character in a particular column in python

I have my data as say df-

data = [['Gs01', 'safety'],[44325, 'eLearning_since_2001'],[889, 'air exhaust_open_chamber'],['Fireman\9801','internal_fireman']]
df1 = pd.DataFrame(data, columns = ['e code', 'training'])
df1


e code     training
Gs01         safety
44325        eLearning_since_2001
889          air exhaust_open_chamber
Fireman\9801 internal_fireman

In e code column, it is the employee code and there is some code which I want to delete the row for these codes only like - Gs01, Fireman9801 because it contains string and some characters which is not a genuine employee code, and deleted row must be stored in any other dataframe say excluded_df so my OP should be - df1-

e code     training
44325        eLearning_since_2001
889          air exhaust_open_chamber

excluded_df-

e code     training
Gs01         safety
Fireman\9801 internal_fireman

Please help me to achieve the above result using python, thanks in advance.

Upvotes: 1

Views: 358

Answers (1)

sophocles
sophocles

Reputation: 13821

Using the data you posted:

>>> df1.to_dict()

{'e code': {0: 'Gs01', 1: 44325, 2: 889, 3: 'Fireman\\9801'},
 'training': {0: 'safety',
  1: 'eLearning_since_2001',
  2: 'air exhaust_open_chamber',
  3: 'internal_fireman'}}

>>> df1

         e code                  training
0          Gs01                    safety
1         44325      eLearning_since_2001
2           889  air exhaust_open_chamber
3  Fireman\9801          internal_fireman

Applying this code:

new = df1[pd.to_numeric(df1['e code'], errors='coerce').notnull()]

Yields back:

  e code                  training
1  44325      eLearning_since_2001
2    889  air exhaust_open_chamber

Upvotes: 1

Related Questions