Yassine
Yassine

Reputation: 199

Extract a dataframe from a dataframe

I have a dataframe (say "tst" in the code below) from which, I want to construct a new dataframe (that I named by "WhatIwant"). In brief : I've dropped some rows and columns to find a reduced dataframe. Is there any (pythonic) way to do it directly aside from dropping rows and columns ?

tst = pd.DataFrame({'a': np.arange(7), 'b': np.arange(8,15), 'c': np.arange(16,23), 'd': np.arange(24,31)})

What I want to find:

WhatIwant = pd.DataFrame({'a': [0,3,5], 'c': [16,19,21], 'd': [24,27,29]})

Thanks

Upvotes: 0

Views: 307

Answers (2)

AChampion
AChampion

Reputation: 30288

Assuming you just want rows 0, 3, 5 and not column b then:

In []:
WhatIwant = tst.loc[[0,3,5], tst.columns != 'b'].reset_index(drop=True)
WhatIwant

Out[]:
   a   c   d
0  0  16  24
1  3  19  27
2  5  21  29

Upvotes: 2

ilmarinen
ilmarinen

Reputation: 5757

Pandas has got the loc accessor for just these purposes

>>> tst.loc[(0, 3, 5), ('a', 'c', 'd')]
a   c   d
0  0  16  24
3  3  19  27
5  5  21  29

Upvotes: 2

Related Questions