繁体   English   中英

根据Python Pandas中的条件减去两行

[英]Subtract two rows based on condition in Python Pandas

我正在使用一个数据集,我有时间和几种不同种类的微生物的浓度重复,所以它只是一个时间列和一堆数字为了这个问题。 我每两个小时进行一次测量,有时我会连续进行两次测量,这些测量的时间戳会非常相似。 对于那些类似的时间戳,我想取所有列的两行的平均值,并将这些平均值返回到之前放置两个值的新数据帧。

这是数据框的样子。 时间戳已转换为数值,因为相对时间/日期无关紧要。 你可以看到我正在谈论的一个例子,在第9和第10个索引有两个非常相似的时间

      Time        A1       A2       A3
 0    0.000069    118.0    108.0    70.0
 1    0.087049    189.0    54.0     89.0
 2    0.156551    154.0    122.0    107.0
 3    0.721516    129.0    148.0    148.0
 4    0.789329    143.0    162.0    212.0
 5    0.882743    227.0    229.0    149.0
 6    0.964907    208.0    255.0    241.0
 7    1.041424    200.0    241.0    222.0
 8    1.731806    733.0    838.0    825.0
 9    1.794340    804.0    996.0    954.0
10    1.794769    861.0    987.0    1138.0

将时间列中的数字四舍五入到一个合理的值似乎是显而易见的,我可以使用groupby()函数(如果我实际上需要对它们进行分组)然后平均“重复”值,但我已经下了一个新的哲学之路,我想用pandas iterrows()函数来遍历行,逐个1,并比较每两个连续的行并对它们应用一个条件来实现相同的结果。 我已经到达了这样的东西,它没有错误代码,但似乎没有做任何事情。

for i, row in df.iterrows():
    row2 = row + 1 #I feel like this line is the crux of the problem
    if row2.Time - row.Time >= 0.1:
        row = (row2 + row)/2
    else:
        row = row

出于好奇,我很想知道哪个更快,分组和平均方式或for循环和平均方式。 也许有一个漂亮的lamba函数方式来做到这一点? 我已经广泛搜索过这种类型的东西,我很想知道你们都能想出什么。

干杯

以下是一些一般提示:

  • 首选python for循环的矢量化计算。 例如,调用df['Time'].diff()比在循环中计算row2['Time'] - row1['Time']要快得多。 对于足够大的N ,向量化计算将总是超过for循环计算,其中Nfor-loop所需的迭代次数。
  • 优先选择基于行的操作的基于列的操作
  • 与较小阵列上的许多操作相比,在大型阵列上的操作更少。

作为原理的演示,请考虑这两种计算所需结果的不同方法:

import numpy as np
import pandas as pd

df = pd.DataFrame({'A1': [118.0, 189.0, 154.0, 129.0, 143.0, 227.0, 208.0, 200.0, 733.0, 804.0, 861.0], 'A2': [108.0, 54.0, 122.0, 148.0, 162.0, 229.0, 255.0, 241.0, 838.0, 996.0, 987.0], 'A3': [70.0, 89.0, 107.0, 148.0, 212.0, 149.0, 241.0, 222.0, 825.0, 954.0, 1138.0], 'Time': [6.8999999999999997e-05, 0.087049000000000001, 0.156551, 0.72151599999999994, 0.78932899999999995, 0.88274300000000006, 0.96490699999999996, 1.0414239999999999, 1.7318060000000002, 1.79434, 1.7947689999999998]}) 

def using_loop(df):
    for i in range(len(df)-1):
        row1, row2 = df.iloc[i], df.iloc[i+1]
        if row2['Time'] - row1['Time'] >= 0.1:
            df.iloc[i] = (row2 + row1)/2
    return df

def using_column_based_operations(df):
    mask = df['Time'].diff() >= 0.1
    prior = mask.shift(-1).fillna(False)
    df.loc[prior] = (df.loc[mask].values+df.loc[prior].values)/2
    return df

In [220]: using_loop(df).equals(using_column_based_operations(df))
Out[220]: True

下面是一个使用IPython的的基准%%timeit函数,它显示using_column_based_operations是数千倍的速度比using_loopnrows是10 ** 4。 随着nrows增加, using_column_based_operations的速度优势using_column_based_operations增加。

In [216]: nrows, ncols = 10**4, 4

In [217]: %%timeit df = pd.DataFrame(np.random.random((nrows, ncols)), columns=['Time', 'A1', 'A2', 'A3'])
   .....: using_loop(df)
   .....: 
1 loop, best of 3: 3.02 s per loop

In [218]: %%timeit df = pd.DataFrame(np.random.random((nrows, ncols)), columns=['Time', 'A1', 'A2', 'A3'])
   .....: using_column_based_operations(df)
   .....: 
1000 loops, best of 3: 1.91 ms per loop

暂无
暂无

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

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