Home > Blockchain >  Selecting first n columns and last n columns with pandas
Selecting first n columns and last n columns with pandas

Time:10-01

I am trying to select the first 2 columns and the last 2 column from a data frame by index with pandas and save it on the same dataframe.

is there a way to do that in one step?

CodePudding user response:

You can use the iloc function to get the columns, and then pass in the indexes.

df.iloc[:,[0,1,-1,-2]]

CodePudding user response:

You are looking for iloc:

df = pd.DataFrame([[1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]], columns=['a','b','c','d','e'])

df.iloc[:,:2] # Grabs all rows and first 2 columns
df.iloc[:,-2:] # Grabs all rows and last 2 columns

pd.concat([df.iloc[:,:2],df.iloc[:,-2:]],axis=1) # Puts them together row wise

CodePudding user response:

df = pd.DataFrame([[1,2,3,4,5], [2,3,4,5,6], [3,4,5,6,7]], columns=['a','b','c','d','e'])

df[['a','b','d','e']]

result

    a   b   d   e
0   1   2   4   5
1   2   3   5   6
2   3   4   6   7
  • Related