pukumarathe
pukumarathe

Reputation: 71

Column Based Row Slices

The question is as follows. I have a dataframe like below. And I would like to slice based on row

Index A B
0 0 1
1 0 1
2 1 0
3 1 0
4 1 0
5 1 0
6 0 1
7 0 1
8 1 0
9 1 0
10 0 1

And I would like to slice rows based on a particular combinations of rows. For example, below

Index A B
2 1 0
6 0 1
8 1 0
10 0 1

So slice combination should be,

A B
1 0
0 1

Tried a few things with multi-index slicing, row difference but couldn’t get above product dataframe. Any help on this is appreciated. Thanks.

Upvotes: 0

Views: 58

Answers (1)

Rafael MR
Rafael MR

Reputation: 303

try this

import pandas as pd

d = {'A' : [0,0,1,1,1,1,0,0,1,1,0],
'B' : [1,1,0,0,0,0,1,1,0,0,1]
}
df = pd.DataFrame(data = d)

print(df)

list_a = []
list_b = []
test = 1
for x in range(0, len(df['A'])):
    if (df['A'][x] == 1 and test == 1):
        list_a += [1]
        list_b += [0]
        test = 0 
    elif (df['B'][x] == 1 and test == 0):
        list_b += [1]
        list_a += [0]
        test = 1
    elif (df['A'][x] == 1 and x == 0):
        list_a += [1]
        list_b += [0]

new_d = {'A' : list_a,
         'B' : list_b}
new_df = pd.DataFrame(data = new_d)

print("________BREAK__________\n\n")
print(new_df)

OUTPUT

   A  B
0  1  0
1  0  1
2  1  0
3  0  1

Upvotes: 1

Related Questions