鍍金池/ 問答/數(shù)據(jù)分析&挖掘  Python  HTML/ Pandas 如何篩選? 條件為目標(biāo)列的后值大于前值

Pandas 如何篩選? 條件為目標(biāo)列的后值大于前值

   A  B
0  1  1
1  1  2
2  1  3
3  1  4
4  1  3
5  1  6
6  1  7

需要根據(jù)B列篩選,條件為目標(biāo)列的后值大于前值,把index=4的這行去掉。

請(qǐng)問該怎么寫切片語句?謝謝!

回答
編輯回答
別傷我

df.drop(df.index[1:][df.B[1:]<df.B[:-1]])


需要根據(jù)B列篩選,條件為目標(biāo)列的后值大于前值,把index=4的這行去掉

@zoujj

>>> import pandas as pd
>>> df = pd.DataFrame(list(range(1,8)),columns=['B'])
>>> df.B[4]=3
>>> df['A']=1
>>> df
   B  A
0  1  1
1  2  1
2  3  1
3  4  1
4  3  1
5  6  1
6  7  1
>>> df[(df.B[1:]<df.B[:-1])] # @zoujj 的方法是錯(cuò)的
Traceback (most recent call last):
  File "<pyshell#21>", line 1, in <module>
    df[(df.B[1:]<df.B[:-1])]
……
pandas.core.indexing.IndexingError: Unalignable boolean Series key provided
>>> df.drop(df.index[1:][df.B[1:]<df.B[:-1]])
   B  A
0  1  1
1  2  1
2  3  1
3  4  1
5  6  1
6  7  1
>>> 
2017年9月18日 13:41
編輯回答
久不遇

df[(df.B[1:]<df.B[:-1])]
百度這個(gè)教程講得非常明白:https://jingyan.baidu.com/art...

2017年6月13日 13:36
編輯回答
雨蝶

想了一種辦法,增加一列C,用B列去第一位,增加最后一位
C列的值為:[2, 3, 4, 3, 6, 7, 7]
然后取C列大于等于B列的行,就是你要的值

import pandas as pd

df = pd.read_table('a.txt')
lst = list(df['B'])
df['C'] = lst[1:] + [lst[-1]]
print df[df['C'] >= df['B']]
2017年7月3日 04:08
編輯回答
巫婆
import pandas as pd
df = pd.DataFrame(list(range(1,8)),columns=['B'])
df.B[4]=3
df['A']=1
df[df["B"].shift(1).fillna(method="bfill")<df["B"]]
2017年11月5日 04:11