python - Pandas 中将元组分配给段的最有效方法

标签 python pandas

我编写了以下代码段,它将元组分配给段。段是元组的容器,跨越一定的时间间隔。与只有 1 个时间戳的元组相反。

但是,由于我的代码有大约 30 000 个元组,并且此步骤经常迭代,因此在此方法上花费了大量时间。

有没有更有效的方法来处理这个问题?

for timestamp, tuple in tuples.iterrows():
    this_seg = [s for s in segments if s.can_have(timestamp)]
    assert(len(this_seg) <= 1)
    for s in this_seg:
        s.append(tuple)
return segments

这里有更多背景信息:

segment是Segment类型的类,并且具有如下构造函数:

def __init__(self, ts_max, ts_min):
            self._df = pd.DataFrame({})
            self._ts_max = ts_max
            self._ts_min = ts_min

can_have 方法检查给定的时间戳是否可以是该段的一部分:即时间戳位于 ts_min 和 ts_max 之间。

Tuples 是一个 Pandas 数据帧,它以时间戳作为索引,并以其他一些功能作为列。

最佳答案

Iterrows 是 Pandas 中最慢的处理方式。从您的问题中不清楚您想要做什么,但本教程提供了几种更快的 iterrows 替代品。

https://realpython.com/fast-flexible-pandas/

关于python - Pandas 中将元组分配给段的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53816399/

相关文章:

python - 如何对字符串形式的数字列表的数据框列求和?

python - Seaborn countplot,每组归一化 y 轴

python - 在 python 中使用 reduce() 序列化一个字符串

python - django2.1 发送电子邮件失败 :ssl. SSLError : [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl. c:833)

list - 如何从 Pandas 数据框中制作列表列表,跳过 nan 值

python - 使用 pandas 创建一个由 DataFrame 中的列表组成的新列

python - 从标签为元组的 pandas 系列中进行选择

python - 如何在排除一种可能性的情况下随机选择列表中的项目?

python - 异常必须是旧式类或派生自 BaseException,而不是 NoneType

python - 从 numpy 数组计算椭圆内的像素