【问题标题】:Slicing data with Multiindex columns使用多索引列对数据进行切片
【发布时间】:2019-11-14 05:58:03
【问题描述】:

我有一个带有 MultiIndex 列的数据框。我想使用数据集的列过滤数据。当我尝试df.columns 时,我得到了以下信息:

MultiIndex(levels=[['power'], ['active']],
           codes=[[0], [0]],
           names=['physical_quantity', 'type'])

数据集的简短描述是:

physical_quantity          power
type                      active
2011-04-18 09:22:13-04:00    6.0
2011-04-18 09:22:16-04:00    6.0
2011-04-18 09:22:20-04:00    6.0
2011-04-18 09:22:23-04:00    6.0
2011-04-18 09:22:26-04:00    6.0

我发现的第一件事是,虽然你在那里看到两列,但数据框确实说它是[529757 rows x 1 columns] 的数据集。

我要做的是过滤选择时间间隔的数据,选择名为physical_quantity type的第一列。

另一方面,第一列(physical_quantity type)的数据是未知的:

physical_quantity  type  
power              active    float32
dtype: object

检查df.index 我设法看到了有关数据框的信息:

DatetimeIndex(['2011-04-18 09:22:13-04:00', '2011-04-18 09:22:16-04:00',
               '2011-04-18 09:22:20-04:00', '2011-04-18 09:22:23-04:00',
               '2011-04-18 09:22:26-04:00', '2011-04-18 09:22:30-04:00',
               '2011-04-18 09:22:33-04:00', '2011-04-18 09:22:37-04:00',
               '2011-04-18 09:22:40-04:00', '2011-04-18 09:22:44-04:00',
               ...
               '2011-05-14 23:59:26-04:00', '2011-05-14 23:59:29-04:00',
               '2011-05-14 23:59:33-04:00', '2011-05-14 23:59:36-04:00',
               '2011-05-14 23:59:40-04:00', '2011-05-14 23:59:43-04:00',
               '2011-05-14 23:59:46-04:00', '2011-05-14 23:59:50-04:00',
               '2011-05-14 23:59:53-04:00', '2011-05-14 23:59:57-04:00'],
              dtype='datetime64[ns, US/Eastern]', length=529757, freq=None)

所以我了解到该列的数据类似于dtype='datetime64[ns, US/Eastern]

所以我的目标是将数据从特定的日期和时间分割到另一个日期和时间。

从 2011-05-10 19:44:51-04:00 到 2011-05-10 23:17:59-04:00

我试着做这样的事情:

df[df['physical_quantity', 'type']] > 2011-05-10 19:44:51-04:00 
& 
df[df['physical_quantity', 'type']] < 2011-05-10 23:17:59-04:00
df[df['physical_quantity', 'type']] > 2011-05-10 19:44:51-04:00

File "<ipython-input-133-27848c7d6afc>", line 1
    df[df['physical_quantity', 'type']] > 2011-05-10 19:44:51-04:00
                                                ^
SyntaxError: invalid token

我该如何解决我的问题?

【问题讨论】:

  • 就其本身而言,2011-05-10 19:44:51-04:00 不是 Python 的有效对象,解释器不明白如何处理这个问题。它是 int、float 还是 string?您应该比较兼容的数据类型,在这种情况下是两个 np.datetime64 或 datetime.datetime 对象。看看thesetwo 案例,以防万一。

标签: python pandas dataframe


【解决方案1】:

试试这个

df['ts'] = pd.to_datetime(df["ts"], unit="ms")```

【讨论】:

  • 虽然这段代码 sn-p 可能会回答这个问题,包括对为什么和如何的解释,它有助于解决问题,提高质量和寿命你的回答。见"How do I write a good answer?"。
猜你喜欢
  • 2014-05-02
  • 2018-03-12
  • 2021-12-07
  • 2020-02-27
  • 1970-01-01
  • 2014-07-31
  • 1970-01-01
  • 2018-11-07
相关资源
最近更新 更多