簡體   English   中英

基於條件表達式、迭代 (n) 和 (n+1) 從 pandas DataFrame 中刪除行

[英]Delete rows from a pandas DataFrame based on a conditional expression, iteration (n) and (n+1)

給定一個 dataframe 如下:

 col1 
1  0.6   
2  0.88  
3  1.2  
4  1.2  
5  1.2  
6  0.55  
7  0.55
8  0.65

我想從中刪除行(n + 1)中的值與(n)中的值相同的行,這樣會產生:

col1 
1  0.6   
2  0.88  
3  1.2  
4  row deleted  
5  row deleted  
6  0.55  
7  row deleted
8  0.65
In [191]: df[df["col1"] != df["col1"].shift()]
Out[191]:
   col1
1  0.60
2  0.88
3  1.20
6  0.55
8  0.65

嘗試這個:

df = df[~df['col1'].eq(df['col1'].shift(1))]
print(df)

   col1
0  0.60
1  0.88
2  1.20
5  0.55
7  0.65

或者:

df = df[df['col1'].ne(df['col1'].shift(1))]
print(df)

   col1
0  0.60
1  0.88
2  1.20
5  0.55
7  0.65

好吧,讓我們做

df=df[df.diff().ne(0)]

暫無
暫無

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

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