Note: my question isn't this one, but something a little more subtle.
Say I have a dataframe that looks like this
df =
A B C
0 3 3 1
1 2 1 9
df[["A", "B", "D"]]
will raise a KeyError
.
Is there a python pandas way to let df[["A", "B", "D"]] == df[["A", "B"]]
? (Ie: just select the columns that exist.)
One solution might be
good_columns = list(set(df.columns).intersection(["A", "B", "D"]))
mydf = df[good_columns]
But this has two problems:
mydf.columns
could be ["A", "B"]
or ["B", "A"]
.You can use filter
, this will just ignore any extra keys:
df.filter(["A","B","D"])
A B
0 3 3
1 2 1