piRSquared piRSquared - 1 year ago 89
Python Question

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



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

enter image description here

col_list = list('bcd')


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 Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download