簡體   English   中英

如何在熊貓數據框中找到連續值的最后一個值?

[英]how to find the last value of consecutive values in pandas dataframe?

我有一個這樣的數據框

df:
col1     col2
 1        10
 1        20
 2        11
 3        33
 1        20
 1        10
 2        24
 3        21
 3        28

我想在col1上有連續值的數據幀中進行分組,並為每個連續組取最后一個值,

最終的數據幀應如下所示:

df
col1    col2
 1       20
 2       11
 3       33
 1       10
 2       24
 3       28

我已經嘗試過類似的東西:

 df['b_new'] = df.groupby('col1')['col2'].transform('last')

但是它缺少連續條件。

如何使用pandas / python以最有效的方式實現它

對最后重復的連續行使用boolean indexing ,將Series.neSeries.shift ed Series一起使用-1過濾:

df1 = df[df['col1'].ne(df['col1'].shift(-1))]
print (df1)
   col1  col2
1     1    20
2     2    11
3     3    33
5     1    10
6     2    24
8     3    28

詳細說明

print (df['col1'].ne(df['col1'].shift(-1)))
0    False
1     True
2     True
3     True
4    False
5     True
6     True
7    False
8     True
Name: col1, dtype: bool

暫無
暫無

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

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