0

I have a function that I am able to apply to a dataframe column, df['X'].

df['X'].str[:-2].str.zfill(2).apply('="{}"'.format).str.replace(' ', '')

Which returns ="08", Or ="03" within the column itself. However I only want to apply this condition if the column value is not equal to np.nan. Just wondered how you could apply such functions subject to an if statement?

df['X'] = df.apply(lambda x: x['X'].str.zfill(3).apply('="{}"'.format).str.replace(' ', '') if x['X'] != np.nan else x, 1). 

I've tried this which I thought might work, but an error returns stating:

"AttributeError: ("'str' object has no attribute 'str'", 'occurred at index 0')"

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • `if somevalue != np.nan: do something` – Barb Oct 28 '19 at 23:13
  • df['X'] = df.apply(lambda x: x['X'].str.zfill(3).apply('="{}"'.format).str.replace(' ', '') if x['X'] != np.nan else x, 1). I've tried this which I thought would work? –  Oct 29 '19 at 08:00

0 Answers0