take subset from a dataframe

Viewed 57

i'm planning to take a subset from a dataframe.

A B C Label
3 2 3 chair
2 4 5 table
3 2 3 table
2 4 5 chair
3 2 3 drawer
2 4 5 drawer
3 2 3 chair
2 4 5 table

i know the first step is to group by the dataframe based on the label. Then i want to take a subset of row with only label "chair", "chair & table", "chair & table & drawer" and put it into a new dataframe (there will be 3 separate dataframe in the end). Is it possible to do this if i turn the data into numpy array and separate the label?

Thank you!

2 Answers

IIUC, you can simply select the required rows of your DataFrame like so:

df1 = df[df["Label"]=="chair"]
df2 = df[df["Label"].isin(["chair", "table"])]
df3 = df[df["Label"].isin(["chair", "table", "drawer"])]

You can use a dictionary with boolean indexing here which should solve it dynamically:

u = df['Label'].unique()
l = [u[:e+1] for e in range(len(u))]
d = {' & '.join(i):df[df['Label'].isin(i)] for i in l}

print(d['chair'],'\n------\n',d['chair & table'],'\n------\n',d['chair & table & drawer'])

 A  B  C  Label
0  3  2  3  chair
3  2  4  5  chair
6  3  2  3  chair 
------
    A  B  C  Label
0  3  2  3  chair
1  2  4  5  table
2  3  2  3  table
3  2  4  5  chair
6  3  2  3  chair
7  2  4  5  table 
------
    A  B  C   Label
0  3  2  3   chair
1  2  4  5   table
2  3  2  3   table
3  2  4  5   chair
4  3  2  3  drawer
5  2  4  5  drawer
6  3  2  3   chair
7  2  4  5   table
Related