Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Going over the dataframe to locate rows where there is datetime.datetime object

Suppose I have the following dataframe:

d = {'col1':['a','b','c'],
    'col2':['d','e', date(2019, 4, 13)],
    'col3':[1,date(2015, 5, 10),3]}
df = pd.DataFrame(d)

I want to locate the rows where there is datetime objects. The outcome would be

 index col1        col2        col3
0      1    b           e  2015-05-10
1      2    c  2019-04-13           3

The reason I am asking this is because in my actual dataframe I get the following error:

TypeError: must be real number, not datetime.datetime

Meaning, somewhere in the dataframe there is a datetime.datetime value where it should not be. So I want to go through the who dataframe and find exactly those rows by object type and drop them eventually.

question from:https://stackoverflow.com/questions/65832503/going-over-the-dataframe-to-locate-rows-where-there-is-datetime-datetime-object

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

1 Answer

0 votes
by (71.8m points)

Try applymap:

mask = df.applymap(lambda x: type(x) == datetime.date).any(1)
df[mask]

Output:

  col1        col2        col3
1    b           e  2015-05-10
2    c  2019-04-13           3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...