熊猫DataFrame.loc返回空DataFrame

时间:2018-09-12 05:15:37

标签: python pandas dataframe

当前尝试通过一些教程。现在我有一个带有股票数据的熊猫数据框。通过读取一个csv文件获取库存数据,然后使用df.set_index('timestamp', inplace = True)将索引设置为使用“时间戳”。头部在这里看到:

 timestamp   open   high    low   close  adjusted_close   volume  dividend_amount  split_coefficient
2018-09-11  74.95  75.69  74.76  75.64           75.64  2225700              0.0                1.0
2018-09-10  75.10  75.21  74.84  74.91           74.91  1774400              0.0                1.0
2018-09-07  75.20  75.20  74.72  75.01           75.01  1804800              0.0                1.0
2018-09-06  74.95  75.55  74.62  75.24           75.24  3058300              0.0                1.0
2018-09-05  75.03  75.42  74.80  74.95           74.95  2418400              0.0                1.0

当我尝试df.loc['2018-09-05']时,它会向我返回正确的行。但是,当我尝试选择一个范围,例如df.loc['2018-09-05':'2018-09-11']时,我得到的是一个空数据框,如下所示:

Empty DataFrame
Columns: [open, high, low, close, adjusted_close, volume, dividend_amount, 
split_coefficient]
Index: []

想知道是否有人可以提供有关为什么发生这种情况的见解?我希望在两个日期之间返回信息,而不是返回空的数据框。谢谢!

5 个答案:

答案 0 :(得分:3)

sort_index()在切片之前会起作用:

df = df.sort_index()
df['2018-09-05':'2018-09-11']

df = df.sort_index()
df.loc['2018-09-05':'2018-09-11']

仅供参考:如果您想先确定索引为DatetimeIndex,然后再将'timestamp'作为索引:

df.timestamp = pd.to_datetime(df.timestamp)
df = df.set_index('timestamp')

或之后的事实:

df.index = pd.to_datetime(df.index)

答案 1 :(得分:0)

因为您需要从上至下正确插入索引。 尝试使用此方法进行特定的索引编制:

df.loc['2018-09-11':'2018-09-05']

但是您可以使用sort()对索引进行排序。
您也可以为此使用ID。

答案 2 :(得分:0)

如果timestamp列是“熊猫时间戳记”,则可以执行以下操作。

mask = (df['timestamp'] >= pd.Timestamp('2018-09-05')) & (df['timestamp'] <= pd.Timestamp('2018-09-11'))

df.loc[mask, :]

答案 3 :(得分:0)

您只需要将日期从较新的日期转换为较旧的日期即可使用。

import pandas as pd
df = pd.read_csv('some.csv', delimiter=";", index_col='timestamp')
range = df.loc['2018-09-11':'2018-09-05']
print(range)

答案 4 :(得分:0)

如果您更改日期格式,则可以使用

df.loc['05/09/2018': '11/09/2018']
相关问题