pandas 在 for 循环中删除列的有效方法

NFe*_*ine 2 python dataframe pandas

我有一个要从数据框中删除的列列表。我不知道所有列是否都存在于多个数据帧中,这就是为什么我想迭代它们并删除存在的列。例如:

cols = ['one', 'two', 'three']
for col in cols:
    try:
        df = df.drop(col, axis=1)
    except:
        pass
Run Code Online (Sandbox Code Playgroud)

有没有更有效的方法可以节省时间/处理能力?

moz*_*way 5

您可以设置errors='ignore'

df = df.drop(cols, axis=1, errors='ignore')
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用索引intersection

cols = ['one', 'two', 'three']

df = df.drop(df.columns.intersection(cols), axis=1)
Run Code Online (Sandbox Code Playgroud)

或者difference

df = df[df.columns.difference(cols)]
Run Code Online (Sandbox Code Playgroud)