Home > Enterprise >  Converting existence of any text in a pandas column to a number value
Converting existence of any text in a pandas column to a number value

Time:11-06

I can't seem to find this specific question but hopefully it's an easy one. I have a pandas dataframe with a column with mixed numbers and text. I just want to convert any text instances in that column to the value 999. e.g. for column B, I'd like to perform this operation on, so:

A  B
1  1
2  5
3  FDS
4  EWR
5  7
6  3
7  BB
8  C

becomes...

A  B
1  1
2  5
3  999
4  999
5  7
6  3
7  999
8  999

CodePudding user response:

With np.where clause Series.str.isnumeric:

df['B'] = np.where(df['B'].str.isnumeric(), df['B'], 999).astype(int)

   A    B
0  1    1
1  2    5
2  3  999
3  4  999
4  5    7
5  6    3
6  7  999
7  8  999

CodePudding user response:

Another way:

df['B'] = pd.to_numeric(df['B'], errors='coerce').fillna(999).astype(int)

df after:

   A    B
0  1    1
1  2    5
2  3  999
3  4  999
4  5    7
5  6    3
6  7  999
7  8  999
  • Related