Sahil Sahil - 2 months ago 7
Python Question

Selecting values from a series in pandas

I have a dataset D with Columns from [A - Z] in total 26 columns. I have done some test and got to know which are the useful columns to me in a series S.

D #Dataset with columns from A - Z
S
B 0.78
C 1.04
H 2.38


S has the columns and a value associated with it, So I now know their importance and would like to keep only those Columns in the Dataset eg(
B
,
C
,
D
) How can I do it?

Answer

IIUC you can use:

cols = ['B','C','D']
df = df[cols]

Or if column names are in Series as values:

S = pd.Series(['B','C','D'])
df = df[S]

Sample:

df = pd.DataFrame({'A':[1,2,3],
                   'B':[4,5,6],
                   'C':[7,8,9],
                   'D':[1,3,5],
                   'E':[5,3,6],
                   'F':[7,4,3]})

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

S = pd.Series(['B','C','D'])
print (S)
0    B
1    C
2    D
dtype: object

print (df[S])
   B  C  D
0  4  7  1
1  5  8  3
2  6  9  5

Or index values:

S = pd.Series([1,2,3], index=['B','C','D'])
print (S)
B    1
C    2
D    3
dtype: int64

print (df[S.index])
   B  C  D
0  4  7  1
1  5  8  3
2  6  9  5