I am trying to select column 1 to 8 and the last column from a data frame. I have some dumb way to do that
step 1: select first 8 column
df1 = df[df.columns[range(9)]]
step 2: select last column
df2 = df[df.columns[-1]]
step 3: combine step1 and step2
df1.join(df2)
is there a better way to do that in one step instead of 3 steps?
Selecting columns based on their name This is the most basic way to select a single column from a dataframe, just put the string name of the column in brackets. Returns a pandas series. Passing a list in the brackets lets you select multiple columns at the same time.
Use smart column indexing:
df.iloc[:, list(range(9)) + [-1]]
Use Concat from Pandas. This works as same as CBIND.
new_df = pd.concat([df.iloc[:,0:8],df.iloc[:,-1:]],axis = 1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With