python - 如果 Dataframe 中的数据属于同一流,如何对它们进行分组?

标签 python python-3.x pandas dataframe

import pandas as pd

row_1 = pd.Series({'Address A': 3647,
                   'Address B': 555,
                   'Total Delay': 1.2})
row_2 = pd.Series({'Address A': 555,
                   'Address B': 3647,
                   'Total Delay': 2.1})
row_3 = pd.Series({'Address A': 4567,
                   'Address B': 555,
                   'Total Delay': 0.6})
df = pd.DataFrame([row_1, row_2, row_3], index = [1, 2, 3])
df.head()

output:

    Address A   Address B   Total Delay                         
1   3647        555         1.2
2   555         3647        2.1
3   4567        555         0.6

假设我有上面的 Dataframe,如果 1 和 2 的行相同,我如何将它们分组为 [3647 555] 并将它们的总延迟添加到 3.3,从而给我一个新的 Dataframe。

我必须为另外 50,000 个数据执行此操作。

    Address A   Address B   Total Delay                         
1   3647        555         3.3
3   4567        555         0.6

最佳答案

首先,我们使用 np.sort 在索引轴(每行)上对地址 A地址 B 进行排序。然后我们对这些列进行 GroupBy 并使用 sum + first:

cols = ['Address B', 'Address A']
df[cols] = np.sort(df[cols])

dfg = df.groupby(cols).agg({'No.':'first',
                            'Total Delay':'sum'}).reset_index()
   Address A  Address B  No.  Total Delay
0       3647        555    1         3.30
1       4567        555    3         0.60

如果您希望列按照确切的顺序排列,请使用DataFrame.reindex:

dfg = dfg.reindex(df.columns, axis='columns')
   No.  Address A  Address B  Total Delay
0    1       3647        555         3.30
1    3       4567        555         0.60

关于python - 如果 Dataframe 中的数据属于同一流,如何对它们进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58905588/

相关文章:

python - 仅使用 pathlib 规范化不存在的路径

python - 如何在 Django 查询集中使用 order_by?

pandas - 如何将多级数据帧加入单级数据帧中的值

python - 如何解决位置插值引起的抖动

python - 使用python在Lambda函数中运行命令wirth SSM

python - 变换预测目标

python - 比较两个数据框并根据查找表删除列

python - 如何将 json 列迭代到列,然后附加原始数据帧?

python - 与 Pandas、xticks 绘图

python - 运行简单的 Python Tornado 应用程序时出现初始化错误