Wiliam
Wiliam

Reputation: 1088

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.

Upvotes: 0

Views: 36

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

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

Upvotes: 2

Related Questions