+2 votes
in Programming Languages by (73.2k points)

From the following dataframe, I want to select columns 'a', 'c' and 'e'. How can I select all rows of these columns of the dataframe?

abcde
AA29196723nn
BB12186712mm
CC451834123mm
DD3419454we
EE3820114qw
FF17174534rt
GG22186723ty
HH12175612yu
II38200056re

1 Answer

+1 vote
by (346k points)
selected by
 
Best answer

There are multiple ways to select all rows of some columns of a dataframe. you can use loc (for label based indexing) or iloc (for positional indexing).

Approach 1: Using column names

>>> df
    a   b     c    d   e
0  AA  29  1967   23  nn
1  BB  12  1867   12  mm
2  CC  45  1834  123  mm
3  DD  34  1945    4  we
4  EE  38  2011    4  qw
5  FF  17  1745   34  rt
6  GG  22  1867   23  ty
7  HH  12  1756   12  yu
8  II  38  2000   56  re
>>> df1=df[['a','c', 'e']]
>>> df1
    a     c   e
0  AA  1967  nn
1  BB  1867  mm
2  CC  1834  mm
3  DD  1945  we
4  EE  2011  qw
5  FF  1745  rt
6  GG  1867  ty
7  HH  1756  yu
8  II  2000  re

Approach 2: using iloc and column numbers.

>>> df2=df.iloc[:,[0,2,4]]
>>> df2
    a     c   e
0  AA  1967  nn
1  BB  1867  mm
2  CC  1834  mm
3  DD  1945  we
4  EE  2011  qw
5  FF  1745  rt
6  GG  1867  ty
7  HH  1756  yu
8  II  2000  re

Approach 3: Using loc and column names.

>>> df3=df.loc[:,['a','c', 'e']]
>>> df3
    a     c   e
0  AA  1967  nn
1  BB  1867  mm
2  CC  1834  mm
3  DD  1945  we
4  EE  2011  qw
5  FF  1745  rt
6  GG  1867  ty
7  HH  1756  yu
8  II  2000  re
>>>        


...