gpt4 book ai didi

python - 如何仅将新索引附加到具有 HDFS 存储的表

转载 作者:行者123 更新时间:2023-11-28 18:18:27 24 4
gpt4 key购买 nike

我将遍历许多数据帧以附加到 hdfs 存储中的表。索引将相互重叠。我只想附加存储中尚未包含索引的行。


MCVE

考虑我的数据框 d1d2:

d1 = pd.DataFrame.from_dict(
{('a', 'x'): {'col': 1}, ('a', 'y'): {'col': 1}}, orient='index')
d2 = pd.DataFrame.from_dict(
{('b', 'x'): {'col': 2}, ('a', 'y'): {'col': 2}}, orient='index')

print(d1, '\n\n', d2)

col
a x 1
y 1

col
a y 2
b x 2

我想完成与以下相同的逻辑:

d1.append(d2.loc[d2.index.difference(d1.index)])

col
a x 1
y 1
b x 2

但我想要将其附加到 hdfs 存储。

我尝试过的

d1.to_hdf('test.h5', 'mytable', format='table')
d2.to_hdf('test.h5', 'mytable', append=True)

pd.read_hdf('test.h5', 'mytable')

col
a x 1
y 1
y 2
b x 2

您可以看到索引 ('a', 'y') 与两个不同的值重复。我假设有一种方法可以在将新行附加到表之前检查表中的索引值。

最佳答案

首先初始化商店可能会有所帮助。然后,您应该能够将数据框分配给 mytable 并像在仅数据框示例中那样使用它。

store = pd.HDFStore('test.h5')

store['mytable'] = d1
store['mytable'].append(d2.loc[d2.index.difference(store['mytable'].index)])

col
a x 1
y 1
b x 2

关于python - 如何仅将新索引附加到具有 HDFS 存储的表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46894493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com