Deepak M Deepak M - 27 days ago 8
Python Question

Multiple Slicing in a dataframe in Python

Say for example if I have a data frame with columns A - Z.


  1. I want to slice column "J" and get back all the columns A - Z excluding the column "J".

  2. I want to slice all columns between A - Z and only get back column "J"



Thanks in Advanced.

Answer

I think you can use DataFrame.pop, for return J column need convert Series to DataFrame by Series.to_frame:

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

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

print (df.pop('J'))
0    5
1    3
2    6
Name: J, dtype: int64

dfJ = df.pop('J').to_frame()
print (dfJ)
   J
0  5
1  3
2  6

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

Another solution:

cols = [col for col in df.columns if col != 'J']
print (df[cols])
   A  B  C  D  F
0  1  4  7  1  7
1  2  5  8  3  4
2  3  6  9  5  3

print (df[['J']])
   J
0  5
1  3
2  6