Python pandas selecting columns from data frame via list of column names

I have a dataframe with lots of columns in it. Now I want to select only certain columns. I saved all the column names that I want to select in the Python list, and now I want to filter my framework according to this list.

I tried to do:

df_new = df[[list]] 

where the list includes all the column names that I want to select.

However, I get an error message:

 TypeError: unhashable type: 'list' 

Any help on this?

+8
python pandas dataframe
source share
1 answer

You can delete one [] :

 df_new = df[list] 

It is also better to use a different name like list , for example. L :

 df_new = df[L] 

It looks like it works, I try to simplify it only:

 L = [] for x in df.columns: if not "_" in x[-3:]: L.append(x) print (L) 

List comprehension :

 print ([x for x in df.columns if not "_" in x[-3:]]) 
+8
source share

All Articles