Home > Back-end >  How to drop only the number in the same column which has string in object type, pandas
How to drop only the number in the same column which has string in object type, pandas

Time:11-06

d = {'col1': ['Son', 2, 'Dad'], 'col2': [3, 4, 5]} df = pd.DataFrame(data=d)

I want to drop change the second row to 'Unknown'

  col1  col2
0  Son     3
1    2     4
2  Dad     5

change to

     col1  col2
0     Son     3
1 Unknown     4
2     Dad     5

CodePudding user response:

pandas str functions make numeric to NaN

df['col1'] = df['col1'].str[:].fillna('Unknown')

output:

df

    col1    col2
0   Son     3
1   Unknown 4
2   Dad     5

CodePudding user response:

you can use regex:

df['col1'] = df['col1'].astype(str)
df['col1'] = df['col1'].str.replace('\d ', 'Unknown') #find numbers and replace with "unknown"
  • Related