繁体   English   中英

尽管'index = None'与熊猫'to_hdf'重复索引

[英]repeated index with pandas 'to_hdf' despite 'index=None'

我想将数据存储在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

谢谢。

默认的熊猫索引为[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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM