Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting a dataframe in python

Tags:

python

pandas

I have a dataframe df=

    Type   ID      QTY_1   QTY_2  RES_1   RES_2
    X       1       10      15      y       N
    X       2       12      25      N       N
    X       3       25      16      Y       Y
    X       4       14      62      N       Y
    X       5       21      75      Y       Y
    Y       1       10      15      y       N
    Y       2       12      25      N       N
    Y       3       25      16      Y       Y
    Y       4       14      62      N       N
    Y       5       21      75      Y       Y

I want the result data set of two different data frames with QTY which has Y in their respective RES. Below is my expected result

df1= 

Type   ID      QTY_1   
X       1       10
X       3       25
X       5       21
Y       1       10 
Y       3       25
Y       5       21

df2 = 

Type   ID      QTY_2
X       3       16  
X       4       62
X       5       75
Y       3       16
Y       5       75
like image 561
Alok Avatar asked Sep 10 '26 03:09

Alok


1 Answers

You can do this:

df1 = df[['Type', 'ID', 'QTY_1']].loc[df.RES_1.isin(['Y', 'y'])]

df2 = df[['Type', 'ID', 'QTY_2']].loc[df.RES_2.isin(['Y', 'y'])]

or

df1 = df[['Type', 'ID', 'QTY_1']].loc[df.RES_1.str.lower() == 'y']

df2 = df[['Type', 'ID', 'QTY_2']].loc[df.RES_2.str.lower() == 'y']

Output:

>>> df1
  Type  ID  QTY_1
0    X   1     10
2    X   3     25
4    X   5     21
5    Y   1     10
7    Y   3     25
9    Y   5     21
>>> df2
  Type  ID  QTY_2
2    X   3     16
3    X   4     62
4    X   5     75
7    Y   3     16
9    Y   5     75
like image 132
sacuL Avatar answered Sep 12 '26 15:09

sacuL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!