Saving columns in specified order when using UseCols in Pandas Read_CSV

I have a csv file with 50 columns of data. I use the Pandas read_csv function to pull out a subset of these columns, using the usecols parameter to select the ones I want:

cols_to_use = [0,1,5,16,8] df_ret = pd.read_csv(filepath, index_col=False, usecols=cols_to_use) 

The problem is that df_ret contains the correct columns, but not in the order specified. They are in increasing order, therefore [0,1,5,8,16]. (By the way, column numbers can vary from run to run, this is just an example.) This is a problem because the rest of the code has arrays that are in the “correct” order, and I would prefer not to reorder all of them.

Is there any smart way for Pandas to pull the columns in that order? Any help would be greatly appreciated!

+7
python pandas dataframe
source share
1 answer

you can reuse the same cols_to_use list to select columns in the desired order:

 df_ret = pd.read_csv(filepath, index_col=False, usecols=cols_to_use)[cols_to_use] 
+5
source share

All Articles