简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM