python - 合并行 pandas 数据框

标签 python pandas dataframe

我有一个 pandas 数据框,如下所示:

df =pd.DataFrame([[0,10,0,'A','A',6,7],[11,21,1,'A','A',8,9],[0,13,1,'B','B',11,13],[0,12,1,'C','C',14,15],[13,14,0,'C','C',16,18]],columns=['Start Sample','End Sample','Value','Start Name','End Name','Start Time','End Time'])

df
Out[18]: 
   Start Sample  End Sample  Value Start Name End Name  Start Time  End Time
0             0          10      0          A        A           6         7
1            11          21      1          A        A           8         9
2             0          13      1          B        B          11        13
3             0          12      1          C        C          14        15
4            13          14      0          C        C          16        18

我想对具有相同 Value 的连续行进行分组如果行 i+1 的开始时间之间存在差异和行的结束时间 i< 3

例如,第 1、2、3 行是具有相同值的连续行。

df['Start Time'].iloc[2] - df['End Time'].iloc[1] is = 2
df['Start Time'].iloc[3] - df['End Time'].iloc[2] is = 1

所以它们都应该合并。 我希望这些行变成:

df2
Out[25]: 
   Start Sample  End Sample  Value Start Name End Name  Start Time  End Time
0             0          10      0          A        A           6         7
1            11          12      1          A        C           8        15
2            13          14      0          C        C          16        18

请注意,新的合并行应具有:

1) Start Sample = to the Start Sample of the first row merged
2) End Sample = to the End Sample of the last row merged
3) Value = to the common value
4) Start Name = to the Start Name of the first row merged
5) End Name = to the End Name of the last row merged
6) Start Time = to the Start Name of the first row merged
7) End Name = to the End Name of the last row merged

最佳答案

首先是一些代码供您考虑,然后是一些解释。这里的方法是根据您的“值”分成子集并处理这些子数据帧。

def agg(series):
    if series.name.startswith('Start'):
        return series.iloc[0]
    return series.iloc[-1]

subsets = [subset.apply(agg) for _, subset in 
             df.groupby((df['Value']!=df['Value'].shift(1)).cumsum())]

pd.concat(subsets, axis=1).T

“棘手”的部分是df['Value']!=df['Value'].shift(1)).cumsum()。这会发现“值”何时发生变化。我们将对其进行分组,但首先 cumsum() 给出唯一值。

groupby之后,您将迭代您感兴趣的数据帧的子集。从这里您可以做很多事情,这就是为什么它很灵活。

对于每个子集,apply 函数将应用于每个系列(列)。在您的情况下,您正在根据列名称查找两个值之一,以便可以将一个函数(此处为agg)应用于每个系列。

编辑:上述更改测试仅包括指定的两个标准 OP 之一。包含两者很容易,但扩展了逻辑,因此应该稍微分解一下。对于这种逻辑,我已经突破了不合理的单线的界限。所以groupby条件应该是:

val_chg = df['Value'] != df['Value'].shift(1)
time_chg = df['Start Time']-df['End Time'].shift(1) >=3

df.groupby((val_chg | time_chg).cumsum())

关于python - 合并行 pandas 数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45079843/

相关文章:

python - 从 DataFrame 列中提取特定字符/文本

python - 嵌套字典到 csv excel

python - 动态服务 django docker 容器

python - Pandas dataframe - 根据两列的 ID 查找匹配的行

python - 如何根据条件检查两行并将其合并为python中的单行

python - 为什么 pandas 中使用的函数行为会发生变化?

python - 将 Fernet key 写入文本文件会生成字节字符串而不是 ASCII 字符串

python - 使用完全外连接连接 pandas 中的两个数据帧

python线性回归以日期为轴

python - 新记录后计算平均值