I am perplexed. I have a list of datetime.datetime objects and a matching datetime.datetime object to one of those in the list. I want to check the index of the selected object. I will not post the code that led to this, but the output should be illuminating enough Observe: This is the successful script:
import pandas as pd
import numpy as np
from datetime import datetime
def nearest(items, pivot):
return min(items, key=lambda x: abs(x-pivot))
currTime = '20120329-224716'
DATE_TIME_FORMAT = '%Y%m%d-%H%M%S'
df = pd.DataFrame({'timeStamp' : ['20120329-224716', '20120329-223340']})
df.to_excel(path + "\\track.xlsx")
df1 = pd.read_excel(path + "\\track.xlsx")
time = df1["timeStamp"]
for idx, item in enumerate(time):
time[idx] = datetime.strptime(item, DATE_TIME_FORMAT)
t = nearest(time, datetime.strptime(currTime, DATE_TIME_FORMAT))
idx = np.where(time==t)[0][0]
print(idx)
# returns 0
print(type(t))
# <class 'datetime.datetime'>
print(type(time[0]))
# <class 'datetime.datetime'>
The following does not.
import pandas as pd
import datetime
import numpy as np
df = pd.DataFrame({'timeStamp' : ['20120329-224716', '20120329-223340']})
DATE_TIME_FORMAT = '%Y%m%d-%H%M%S'
times = df["timeStamp"].tolist()
for idx, item in enumerate(times):
times[idx] = datetime.datetime.strptime(item, DATE_TIME_FORMAT)
t = datetime.datetime.strptime('20120329-224716', DATE_TIME_FORMAT)
print(t)
# 2012-03-29 22:47:16
print(type(t))
# <class 'datetime.datetime'>
print(times[0:1])
# [datetime.datetime(2012, 3, 29, 22, 47, 16), datetime.datetime(2012, 3, 29, 22, 33, 40)]
print(times[0])
# 2012-03-29 22:47:16
print(type(times[0]))
# <class 'datetime.datetime'>
# As you can see, the two objects are datetime.datetime and refer to the same date
print(np.where(times==t))
# (array([], dtype=int64),)
# It is empty, so the next line obviously does not work
idx = np.where(times==t)[0][0]
# IndexError: index 0 is out of bounds for axis 0 with size 0
t = datetime.datetime.strptime('20120329-224717', DATE_TIME_FORMAT)
idx = np.where(times==t)[0][0]
For a strange reason, this was downvoted even though I edited the document. Anyway, I solved the problem by keeping everything as strings. Still confused because the above code works with a different dataset.
Anyway, solution:
import pandas as pd
import datetime
import numpy as np
df = pd.DataFrame({'timeStamp' : ['20120329-224716', '20120329-223340']})
DATE_TIME_FORMAT = '%Y%m%d-%H%M%S'
times = df["timeStamp"].tolist()
print(times)
times_object = []
t = datetime.datetime.strptime('20120329-224716', DATE_TIME_FORMAT)
t = '20120329-224716'
idx = times.index(t)
print(idx)
# 0
In [5]: t
Out[5]: datetime.datetime(2012, 3, 29, 22, 47, 16)
In [6]: times
Out[6]:
[datetime.datetime(2012, 3, 29, 22, 47, 16),
datetime.datetime(2012, 3, 29, 22, 33, 40)]
Equality test on a list is a simple True/False, not an element by element test:
In [7]: times==t
Out[7]: False
A list comprehension works:
In [8]: [x==t for x in times]
Out[8]: [True, False]
We can now use nonzero
to find the True values.
In [9]: np.nonzero(_)
Out[9]: (array([0]),)
The validity of a nonzero/where
depends entirely on the conditional. times==t
returns False, so obviously where
can only return an empty find.
There are other ways of testing a list for items:
In [13]: t in times
Out[13]: True
In [14]: times.index(t)
Out[14]: 0
[14] would raise an error if [13] was False.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.