python - Pandas HDFStore : Omitting Duplicates

标签 python pandas hdfs hdf5 hdfstore

我有一个 HDFStore,我每晚都会在其中输入数据。我想知道系统是否崩溃等,我可能会重新运行进程,所以我想确保如果一行已经存在,那么下次运行进程时 pandas 不会包含它。有没有办法查找重复项而不包含它们?

最佳答案

如果您的 HDFStore 中有唯一索引,您可以使用以下方法:

创建示例 DF:

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

In [35]: df
Out[35]:
          a         b         c
0  0.407144  0.972121  0.462502
1  0.044768  0.165924  0.852705
2  0.703686  0.156382  0.066925
3  0.912794  0.362916  0.866779
4  0.156249  0.625272  0.360799

保存到 HDFStore:

In [36]: store = pd.HDFStore(r'd:/temp/t.h5')

In [37]: store.append('test', df, format='t')

向我们的 DF 添加新行:

In [38]: df.loc[len(df)] = [-1, -1, -1]

In [39]: df
Out[39]:
          a         b         c
0  0.407144  0.972121  0.462502
1  0.044768  0.165924  0.852705
2  0.703686  0.156382  0.066925
3  0.912794  0.362916  0.866779
4  0.156249  0.625272  0.360799
5 -1.000000 -1.000000 -1.000000   # new row, which is NOT in the HDF file

选择重复行的索引:

In [40]: idx = store.select('test', where="index in df.index", columns=['index']).index

检查:

In [41]: df.query("index not in @idx")
Out[41]:
     a    b    c
5 -1.0 -1.0 -1.0

仅将那些尚未保存的行附加到 HDFStore:

In [42]: store.append('test', df.query("index not in @idx"), format='t')

检查:

In [43]: store.select('test')
Out[43]:
          a         b         c
0  0.407144  0.972121  0.462502
1  0.044768  0.165924  0.852705
2  0.703686  0.156382  0.066925
3  0.912794  0.362916  0.866779
4  0.156249  0.625272  0.360799
5 -1.000000 -1.000000 -1.000000   # new row has been added

关于python - Pandas HDFStore : Omitting Duplicates,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41890393/

相关文章:

python - 有条件地将几列替换为 Pandas 中的默认值

python - 将数据框行转换为 Python 集

hadoop - Hbase memstore 手动刷新

rest - webHDFS API 在每次查询时返回异常

python - 删除 QTableView + QAbstractItemModel 中的几行

python - 如何将所有单词组合成一个字符串?

python - 是否有 SqlAlchemy 数据库不可知的 FROM_UNIXTIME() 函数?

python - 将数据限制为所需的值

python - pandas dataframe 将列转换为行

java - 通过Spark覆盖HDFS文件/目录