0

I have derived a pandas datetime type Series with many NA (called a). Here I use the apply method to extract the date to string. Since the NA is a float type, I use pd.isna() to determine the NULL value, However, the result is quite weird.

Code:

a.apply(lambda x:  x.strftime('%Y%m%d') if pd.notna(x) else x)

Result 1

Result 2

Vishwa Mittar
  • 378
  • 5
  • 16
Donnie
  • 38
  • 5
  • Your result (second image) is _not_ in line with the code you have provided (nothing in the code returns a `timedelta`)? – Timus Apr 24 '22 at 14:14
  • Also, please help us helping you and provide a MRE (see [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) and [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/14311263)). And [Please do not upload images of code/data/errors when asking a question](https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-errors-when-asking-a-question). – Timus Apr 24 '22 at 14:15

1 Answers1

0

x.strtime() will return type 'str'. But if x is 'NA', it will return 'pd.NaT', which is of type 'datetime'. Pandas will not support multiple data types for one string, and the reason for your 'strange output.

To avoid this issue, use this line.

a.apply(lambda x:  x.strftime('%Y%m%d') if pd.notna(x) else '')

or

a.apply(lambda x:  x.strftime('%Y%m%d') if pd.notna(x) else pd.NA)
Akash garg
  • 125
  • 6