piRSquared piRSquared - 1 month ago 9
Python Question

get dataframe slice with list of column names where not all columns are in dataframe

consider

df


df = pd.DataFrame(np.ones((2, 3)), columns=list('abc'))
df


enter image description here

col_list = list('bcd')

df[col_list]


generates an error


KeyError: "['d'] not in index"



How do I get as many of the columns as I can?

enter image description here




comprehension wins

enter image description here

Answer

How about:

df[[col for col in list('bcd') if col in df.columns]]

this yields:

     b    c
0  1.0  1.0
1  1.0  1.0
Comments