4

I have the following "TL" column in a pandas dataframe:

ID  TL     
1   alfdjalk
2   jafd;jsa
3
4
5   ajf;dlka;fd
6   ajdf;k

Right now the TL has dtype of object. The blanks are empty strings.

I want to make the empty strings nulls instead. So I tried the following code:

df_EVENT5_28['TL'] = df_EVENT5_28['TL'].apply(lambda x: x.str.strip()).replace('', np.nan)

But I'm getting the error below: AttributeError: 'str' object has no attribute 'str'

Thoughts?

Asclepius
  • 57,944
  • 17
  • 167
  • 143
PineNuts0
  • 4,740
  • 21
  • 67
  • 112
  • 3
    Have you tried: `df = df.replace('', np.nan)` ? – jpp Mar 22 '18 at 15:58
  • @jpp that is perfect, put it as an answer... It may not help the OP anymore, but it might help others. – Joey Jul 30 '20 at 05:42
  • 1
    This question is not a duplicate. The other questions are about an entire dataframe. This question is about a specific column. That's a significant difference. For a column, you can just use `col[col == ''] = pd.NA`. – Asclepius Dec 07 '20 at 20:29
  • 1
    To add to @jpp 's answer: To change just the one column `TL`: `import numpy as np` and `df['TL'] = df['TL'].replace('', np.nan)`. You can check the correctness by `df['TL'].isnull()` (Unfortunately the question is closed now and answers cannot be added.) – Michal Skop Apr 27 '21 at 13:45

0 Answers0