Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

How to properly declare 'NaT' in a python function to be applied on a pandas dataframe?

I am trying to apply a function to a new pandas dataframe column. The function should return something when pandas row is NaT and something else in all other cases.

The input is a datetime64 class column.

Here's my attempt:

import numpy as np 

def some_fun(x):
    if np.isnat(x) == False:
        return 'something'
    else: 
        return 'something else'

df['new_col'] = np.vectorize(some_fun(df['date']))    

Console Output:

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

data

    date
#0  NaT
#1  NaT
#2  NaT
#3  NaT
#4  2021-01-17
#5  NaT
#6  NaT
#7  NaT
#8  NaT
#9  NaT

Expected output:

    date         new_col
#0  NaT         something else
#1  NaT         something else
#2  NaT         something else
#3  NaT         something else
#4  2021-01-17  something
#5  NaT         something else
#6  NaT         something else
#7  NaT         something else
#8  NaT         something else
#9  NaT         something else

How could I accomplish this task?

question from:https://stackoverflow.com/questions/65942853/how-to-properly-declare-nat-in-a-python-function-to-be-applied-on-a-pandas-dat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The below code does what you want. also, I made some changes to your code.

def some_fun(x):
  
  if pd.isnull(x):
    return 'something else'
  else: 
    return 'something'

df['new_col'] = [some_fun(x) for x in df['date']] 

unfortunately, np.isnat() failed in my code. so I used pd.isnull() instead according to this answer. if you think that'll work for you, use np.isnat().

Output:

output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...