如何纠正错误:
KeyError: 'Passing list-likes to .loc or [] with any missing labels
is no longer supported, see
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#deprecate-loc-reindex-listlike'
我只想获取索引“ ix”中数据框的位置。
这是可重现的样品:
import pandas as pd
ix = pd.DatetimeIndex(["2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", '2019-07-19 13:43:00', '2019-07-19 13:44:00', '2019-07-19 13:45:00', '2019-07-19 13:46:00', '2019-07-19 13:47:00', '2019-07-19 13:48:00', '2019-07-19 13:49:00', '2019-07-19 13:50:00', '2019-07-19 13:51:00', '2019-07-19 13:52:00'], dtype='datetime64[ns]', name='Time', freq=None)
df = pd.DataFrame({"result":[7.445043,0.585584,1.735565,3.217186, 0.211871,0.000000,0.180448,21.645403,22.724170,304.292450]}, index = [
"2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", "2019-07-19 08:50:00", "2019-07-19 08:51:00", "2019-07-19 08:52:00", "2019-07-19 08:53:00", "2019-07-19 08:54:00", "2019-07-19 08:55:00", "2019-07-19 08:56:00" ])
df.index = pd.to_datetime(df.index)
result = df.loc[ix]
print(result)
答案 0 :(得分:1)
要搜索数据框索引,只需将标准列表与df.index.isin
一起使用。
尝试以下代码:
import pandas as pd
from datetime import datetime
# string dates
dtsearch = ["2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", '2019-07-19 13:43:00',
'2019-07-19 13:44:00', '2019-07-19 13:45:00', '2019-07-19 13:46:00', '2019-07-19 13:47:00',
'2019-07-19 13:48:00', '2019-07-19 13:49:00', '2019-07-19 13:50:00', '2019-07-19 13:51:00',
'2019-07-19 13:52:00']
# convert to datetime
dts = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in dtsearch]
# build dataframe
df = pd.DataFrame({"result":[7.445043,0.585584,1.735565,3.217186, 0.211871,0.000000,0.180448,21.645403,
22.724170,304.292450]},
index = ["2019-07-19 08:47:00", "2019-07-19 08:48:00", "2019-07-19 08:49:00", "2019-07-19 08:50:00",
"2019-07-19 08:51:00", "2019-07-19 08:52:00", "2019-07-19 08:53:00", "2019-07-19 08:54:00",
"2019-07-19 08:55:00", "2019-07-19 08:56:00"])
# set df index
df.index = pd.to_datetime(df.index)
# search index using date list
df2 = df[df.index.isin(dts)]
print(df2)
输出
result
2019-07-19 08:47:00 7.445043
2019-07-19 08:48:00 0.585584
2019-07-19 08:49:00 1.735565
答案 1 :(得分:1)
您可以尝试如下操作:
result = df.loc[df.index.intersection(ix)]