胡說(shuō)叔叔
2023-04-18 16:35:36
我有這個(gè)包含 EOD 股票價(jià)格的數(shù)據(jù)集 YAR.OL NHY.OL ... DNB.OL SBO.OLdate ... 1986-03-13 NaN NaN ... NaN NaN1986-03-14 NaN NaN ... NaN NaN1986-03-17 NaN NaN ... NaN NaN1986-03-18 NaN NaN ... NaN NaN1986-03-19 NaN NaN ... NaN NaN... ... ... ... ... ...2020-07-24 377.799988 26.740000 ... 144.500000 51.0000002020-07-27 381.799988 26.350000 ... 142.199997 50.5999982020-07-28 382.399994 26.490000 ... 142.000000 50.2000012020-07-29 377.899994 26.389999 ... 142.100006 50.7999992020-07-30 372.000000 25.049999 ... 137.149994 49.799999索引是日期。但是當(dāng)我嘗試做df.loc[['2020-07-29']]我收到一條錯(cuò)誤消息:KeyError: '2010-07-29'或者當(dāng)我這樣做時(shí):df.loc[['2010-06-29']]我得到KeyError:“[Index(['2010-06-29'], dtype='object', name='date')] 都不在 [index] 中”我在打印df.index的時(shí)候檢查了索引,這個(gè)值是存在的。Index([1986-03-13, 1986-03-14, 1986-03-17, 1986-03-18, 1986-03-19, 1986-03-20, 1986-03-21, 1986-03-24, 1986-03-25, 1986-03-26, ... 2020-07-17, 2020-07-20, 2020-07-21, 2020-07-22, 2020-07-23, 2020-07-24, 2020-07-27, 2020-07-28, 2020-07-29, 2020-07-30], dtype='object', name='date', length=8667)有誰(shuí)知道為什么會(huì)這樣?
2 回答

哆啦的時(shí)光機(jī)
TA貢獻(xiàn)1779條經(jīng)驗(yàn) 獲得超6個(gè)贊
讓我們將索引的 dtype 更改為 datetime 以為數(shù)據(jù)框創(chuàng)建 DateTimeIndex。
df.index = pd.to_datetime(df.index)
現(xiàn)在,讓我們使用df.loc['2010-07-29']
.

慕蓋茨4494581
TA貢獻(xiàn)1850條經(jīng)驗(yàn) 獲得超11個(gè)贊
嘗試這樣訪問(wèn):
df.loc[df['date'] == '2010-06-29']
完整示例:
import pandas as pd
if __name__ == '__main__':
d = {'date': ['2020-08-01', '2020-08-02'], 'test': [3, 4]}
df = pd.DataFrame(data=d)
test = df.loc[df['date'] == '2020-08-01']
print (test)
結(jié)果:
date test
0 2020-08-01 3
添加回答
舉報(bào)
0/150
提交
取消