'Strange output of Python strftime

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



Solution 1:[1]

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)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Akash garg