python中基于索引数据帧的取值

2024-04-18 06:07:39 发布

您现在位置:Python中文网/ 问答频道 /正文

data2 = pd.read_excel(fpath2,header = [0,1,2])
a = data2[1][0] #1 represents month - Jan, 0 represents whether it is weekday

结果是这样的:

Timestamp       L       U
00:00:00   239.90  394.04
01:00:00   228.30  400.57
02:00:00   195.42  395.23
03:00:00   166.02  390.32
04:00:00   143.73  373.59
05:00:00   135.43  355.78
06:00:00    79.48  359.10
........................

我想做的是根据一个特定的时间得到L(低频段)和U(高频段)的值,例如在早上5点。如果有人能帮我,我将不胜感激。你知道吗

加载的文件如下所示:

                           1                 # First header
                  0        |       1         # Second haeder
Timestamp    L    |   U       L    |   U     # Third header
0:00       239.9    394.04  252.9   344.22
1:00       228.3    400.57  240.34  323.33
2:00       195.42   395.23  214.07  288.09
3:00       166.02   390.32  183.05  262.1
4:00       143.73   373.59  158.42  244.5
5:00       135.43   355.78  136.85  419.55
6:00       79.48    359.1   126.33  597.67

我试过了

a = data2[1][0][5:00]

但它给了我空数据帧的结果

Empty DataFrame
Columns: [L, U]
Index: []

当我尝试a=data2[5:00]时,它给了我:

Empty DataFrame
Columns: [(1, 0, L), (1, 0, U), (1, 1, L), (1, 1, U), (2, 0, L), (2, 0, U), (2, 1, L), (2, 1, U), (3, 0, L), (3, 0, U), (3, 1, L), (3, 1, U), (4, 0, L), (4, 0, U), (4, 1, L), (4, 1, U), (5, 0, L), (5, 0, U), (5, 1, L), (5, 1, U), (6, 0, L), (6, 0, U), (6, 1, L), (6, 1, U), (7, 0, L), (7, 0, U), (7, 1, L), (7, 1, U), (8, 0, L), (8, 0, U), (8, 1, L), (8, 1, U), (9, 0, L), (9, 0, U), (9, 1, L), (9, 1, U), (10, 0, L), (10, 0, U), (10, 1, L), (10, 1, U), (11, 0, L), (11, 0, U), (11, 1, L), (11, 1, U), (12, 0, L), (12, 0, U), (12, 1, L), (12, 1, U)]
Index: []

[0 rows x 48 columns]

Tags: columnsdataframereadindexexceltimestampjanempty
3条回答

a[5:00]slicing日期帧。您想使用time类型或字符串对其进行索引,具体取决于Timestamp列的类型:

import datetime
a = a.set_index("Timestamp")

# if it's a string:
a.ix["05:00:00"]

# if it's a timestamp:
a.ix[datetime.time(5)]

如果索引是datetime对象,则可能需要使用datetime对象来引用所需的行。你知道吗

例如,您可以尝试以下操作:

your_time = pd.to_datetime(5, unit = 'h')

然后,再次假设索引是datetime,您可以执行如下标准查询:

df[df.index == your_time]

如果索引不是datetime,请先尝试将其设为datetime

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

5:00不表示时间。你知道吗

下面是一个相关的例子。你知道吗

a = range(10)
print(a[5:00])
print(list(a[5:00]))

给予

range(5,0)
[]

试试“5:00”。你知道吗

相关问题 更多 >