簡體   English   中英

Pandas:將連續行與條件相結合的計算效率最高的方法

[英]Pandas: Most computationally efficient way to combine consecutive rows with conditions

說我有這樣的 dataframe

df = pd.DataFrame({
'position': ['head', 'tail', 'head', 'head', 'head', 'tail', 'tail', 'head'], 
        'start': [2, 13, 54, 320, 654, 677, 3430, 9000],
        'end': [4, 15, 564, 390, 674, 679, 6000, 9010],
    })        #s.  e.   k    k.   s.        e.    k 
df.head(10)

position    start   end
0   head    2   4
1   tail    13  15
2   head    54  564
3   head    320 390
4   head    654 674
5   tail    677 679
6   tail    3430    6000
7   head    9000    9010

我想組合行,如果 position label 如果該行是“頭”,那么連續的 position 是“尾”,那么這些行應該以“開頭”的方式組合並且使用“tail”的“end”值。 並且在“頭”行之后有多個連續的“尾”行,然后將跳過中間的“尾”行。

解釋起來很棘手,但這里有一個示例 dataframe 期望的結果應該是什么樣子

    position    start   end
0   tail    2   15
1   head    54  564
2   head    320 390
3   tail    654 6000
4   head    9000    9010

我使用iterrows想出了這個解決方案

previous = None
list_dicts = []
for idx, row in df.iterrows():
    if row['position'] == 'head':
        if previous:
            package = {'position': previous, 'start':previous_start, 'end':previous_end}
            list_dicts.append(package)
        previous = 'head'
        previous_start = row['start']
        previous_end = row['end']
    elif row['position'] == 'tail':
        previous = 'tail'
        previous_start = previous_start
        previous_end = row['end']
if row['position'] == 'head':
    package = {'position': row['position'], 'start':row['start'], 'end':row['end']}
elif row['position'] == 'tail':
    package = {'position': row['position'], 'start':previous_start, 'end':row['end']}
list_dicts.append(package)

pd.DataFrame(list_dicts).head(10)

但是我讀過應該避免使用 iterrows,因為它不是操作數據幀的計算效率最高的方法。 在這種情況下,我將求助於創建一個全新的 dataframe。 但是在使用基於連續行的條件的情況下,這是我能想到的唯一解決方案。

使用pandas.groupby一種方法:

m = df["position"].eq("head").cumsum()
new_df = df.groupby(m, as_index=False).agg({"position": "last", 
                                            "start": "first", 
                                            "end": "last"})
print(new_df)

Output:

  position  start   end
0     tail      2    15
1     head     54   564
2     head    320   390
3     tail    654  6000
4     head   9000  9010

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM