如果数据帧中的数据流相同,如何对它们进行分组?

2024-04-26 04:17:52 发布

您现在位置:Python中文网/ 问答频道 /正文

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

假设我有上面的数据帧,我如何将1和2分组为[3647555],如果它们在行中是相同的,并将它们的总延迟添加到3.3,从而得到一个新的数据帧。你知道吗

我要再做5万个数据。你知道吗

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


Tags: 数据importdataframepandasdfoutputindexaddress
1条回答
网友
1楼 · 发布于 2024-04-26 04:17:52

首先,我们用np.sort对索引轴(每行)上的Address AAddress 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

相关问题 更多 >