python - 尽管有 'to_hdf',但用 pandas 'index=None' 重复索引

标签 python python-3.x pandas hdfstore

我想将数据存储在 HDFS 文件中,但将新数据附加到该文件会使索引重复。我可以知道如何避免吗?

In [35]: hdf = pd.HDFStore('temp.h5')
In [36]: hdf.is_open
Out[36]: True

In [37]: hdf
Out[37]:
<class 'pandas.io.pytables.HDFStore'>
File path: temp.h5
Empty

使用 index=None 添加值

In [38]: pd.DataFrame(np.random.random((3, 1)), columns=['values'], index=None).to_hdf(hdf, 'rand_values', append=True)

In [39]: hdf
Out[39]:
<class 'pandas.io.pytables.HDFStore'>
File path: temp.h5
/rand_values            frame_table  (typ->appendable,nrows->3,ncols->1,indexers->[index])

# So far so good...
In [40]: hdf['rand_values']
Out[40]:
     values
0  0.258981
1  0.743619
2  0.297104

In [41]: hdf.close()
In [42]: hdf.open()

# Add values again with INDEX=NONE
In [43]: pd.DataFrame(np.random.random((3, 1)), columns=['values'], index=None).to_hdf(hdf, 'rand_values', append=True)

索引现在重复...

In [44]: hdf['rand_values']
Out[44]:
     values
0  0.258981
1  0.743619
2  0.297104
0  0.532033
1  0.242023
2  0.431343

In [45]: hdf.close()
In [46]: hdf.open()

In [47]: hdf['rand_values']
Out[47]:
     values
0  0.258981
1  0.743619
2  0.297104
0  0.532033
1  0.242023
2  0.431343

# Print index
In [48]: hdf['rand_values'].index
Out[48]: Int64Index([0, 1, 2, 0, 1, 2], dtype='int64')

我正在使用 Pandas 0.17.0,Python 3.4.3

谢谢。

最佳答案

默认的 pandas 索引是 [0, 1, 2, ...]。当您说 index=None 时,您实际上只是在说“请使用默认值。”

In [1]: import pandas as pd

In [2]: pd.DataFrame({'x': [10, 20, 30]}, index=None)
Out[2]: 
    x
0  10
1  20
2  30

您可能希望保留一些行并将此值添加到索引

In [5]: df = pd.DataFrame({'x': [10, 20, 30]}, index=None)

In [6]: df.index += 3

In [7]: df
Out[7]: 
    x
3  10
4  20
5  30

关于python - 尽管有 'to_hdf',但用 pandas 'index=None' 重复索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33964781/

相关文章:

python - 将由不同形状的 numpy 数组组成的 numpy 数组保存到 .txt 文件

python - 使用编辑距离替换另一列中的单词

python - 使用 Python 或 Applescript 从网页中提取文本

python - 使用 Python 检索 Twitter 数据时出现 Unicode 解码错误

python - 如何使用 pandas groupby 对多列求和?

python - 按日期对 Pandas 数据集进行排序

python - 用之前的数字替换 Pandas 数据框中的未知数字

python - Scrapy 遗漏了一些 html 元素

python-3.x - 如何在virtualenv中安装gcc

Python pytest pytest_exception_interact 从VCR.py异常自定义异常信息