【问题标题】:HDFStore output in dataframe not series数据框中的 HDFStore 输出不是系列
【发布时间】:2017-05-24 20:52:58
【问题描述】:

我希望将我读入的两个表存储在数据框中。

我正在将一个 h5 文件读入我的代码中:

with pd.HDFStore(directory_path) as store:
    self.df = store['/raw_ti4404']
    self.hr_df = store['/metric_heartrate']

self.df 被存储为一个数据框,而 self.hr_df 被存储为一个系列。

我以相同的方式称呼它们,但我不明白为什么一个是数据框而另一个是系列。这可能与数据的存储方式有关:

任何有关如何将 metric_heartrate 存储为数据框的帮助将不胜感激。

【问题讨论】:

  • 你是如何存储metric_heartrate的——你能发布一个相应的代码吗?好吧,self.hr_df = store['/metric_heartrate'].to_frame('column_name') - 应该修复它...
  • 谢谢。解决了它是的
  • 很高兴。你遇到了很多麻烦来提供帮助

标签: python dataframe hdfstore


【解决方案1】:

很可能metric_heartrate 被存储为系列。

演示:

生成样本 DF:

In [123]: df = pd.DataFrame(np.random.rand(10, 3), columns=list('abc'))

In [124]: df
Out[124]:
          a         b         c
0  0.404338  0.010642  0.686192
1  0.108319  0.962482  0.772487
2  0.564785  0.456916  0.496818
3  0.122507  0.653329  0.647296
4  0.348033  0.925427  0.937080
5  0.750008  0.301208  0.779692
6  0.833262  0.448925  0.553434
7  0.055830  0.267205  0.851582
8  0.189788  0.087814  0.902296
9  0.045610  0.738983  0.831780

In [125]: store = pd.HDFStore('d:/temp/test.h5')

让我们将a 列存储为系列:

In [126]: store.append('ser', df['a'], format='t')

让我们存储一个 DataFrame,只包含一列 - a

In [127]: store.append('df', df[['a']], format='t')

从 HDFStore 读取数据:

In [128]: store.select('ser')
Out[128]:
0    0.404338
1    0.108319
2    0.564785
3    0.122507
4    0.348033
5    0.750008
6    0.833262
7    0.055830
8    0.189788
9    0.045610
Name: a, dtype: float64

In [129]: store.select('df')
Out[129]:
          a
0  0.404338
1  0.108319
2  0.564785
3  0.122507
4  0.348033
5  0.750008
6  0.833262
7  0.055830
8  0.189788
9  0.045610

修复 - 读取 Series 并将其转换为 DF:

In [130]: store.select('ser').to_frame('a')
Out[130]:
          a
0  0.404338
1  0.108319
2  0.564785
3  0.122507
4  0.348033
5  0.750008
6  0.833262
7  0.055830
8  0.189788
9  0.045610

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-25
    • 2017-08-02
    • 2013-07-10
    • 2022-07-21
    • 2015-06-21
    • 2016-09-12
    • 1970-01-01
    相关资源
    最近更新 更多