先找到真正的' pandas数据框中的块值

时间:2017-07-31 13:28:39

标签: python pandas

我有一个数据框,其中一列只包含块中的True或False值。例如:

df =   
            b
  0     False
  1      True
  2      True
  3     False
  4      True
  5      True
  6      True
  7      True
  8     False
  9     False
 10     False
 11     False
 12     False
 13      True
 14      True
 15      True

我需要用True找到块的开头:

>> find_first_true(df)
>> array([1, 4, 13])

任何优雅的解决方案?

修改

感谢您提出的解决方案。我想知道,从我找到的指数开始,提取一定长度块的最简单方法是什么?

例如,我需要在索引之前获取长度为4的块(行数)。所以,如果我的指数(之前发现)

index = array([1, 4, 13])

然后我需要块:

[df.loc[0:4], df.loc[9:13]]

            b
  0     False
  1      True
  2      True
  3     False
  4      True
  9     False
 10     False
 11     False
 12     False
 13      True

我正在循环索引,但想知道更多的pandasian解决方案

3 个答案:

答案 0 :(得分:3)

In [2]: df = pd.read_clipboard()
In [3]: df
Out[3]:
        b
0   False
1    True
2    True
3   False
4    True
5    True
6    True
7    True
8   False
9   False
10  False
11  False
12  False
13   True
14   True
15   True
In [11]: np.where(((df.b != df.b.shift(1)) & df.b).values)[0]
Out[11]: array([ 1,  4, 13], dtype=int64)

答案 1 :(得分:1)

def find_first_true(df):
    #finds indexes of true elements
    a = list(map(lambda e: e[0] + 1 if e[1] else 0, enumerate(df))) 
    a = list(filter(bool, a))
    a = list(map(lambda x: x - 1, a))

    #removes consecutive elements   
    ta = [a[0]] + list(filter(lambda x: a[x] - a[x-1] != 1, range(1, len(a))))  
    a = list(map(lambda x: a[x], ta))   

    return a

答案 2 :(得分:1)

find_first = []
for i in range(len(df)):
    if (df.loc[i, 'b'] == False and df.loc[i+1, 'b'] == True):
        find_first.append(i+1)