我需要经常向数据框(或序列,如果这样更有效)中添加一个,同时确保添加的内容不会创建重复项。随着数据帧的增长,通过简单地将其隐藏然后调用drop_duplicates,这似乎会变得效率低下,因为需要为每个数据集检查整个数据集是否存在重复项。
数据只有两列,因此我猜测将其中一列转换为索引可能会加快速度。(或将两列都放入分层索引中)熊猫有禁止重复索引的方法吗?
这是一个示例问题:
print accumulating_result
c1 c2
0 A x1
1 B x2
2 B x3
3 C x4
print new
c1 c2
0 B x3
1 C x4
2 C x5
执行将new添加到accumulating_result并获得:
print accumulating_result
c1 c2
0 A x1
1 B x2
2 B x3
3 C x4
4 C x5
值多少钱,c2列中的每个条目都是唯一的。
有任何想法吗?
您可以使用combine_first()
:
data1 = """ c1 c2
0 A x1
1 B x2
2 B x3
3 C x4"""
data2 = """ c1 c2
0 X x3
1 Y x4
2 Z x5"""
import io
import pandas as pd
df1 = pd.read_csv(io.BytesIO(data1), delim_whitespace=True)
df2 = pd.read_csv(io.BytesIO(data2), delim_whitespace=True)
df1.set_index("c2", inplace=True)
df2.set_index("c2", inplace=True)
df1.combine_first(df2)
输出:
c1
c2
x1 A
x2 B
x3 B
x4 C
x5 Z
但每次都会复制所有数据。也许使用HDF5或数据库更好。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句