Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop columns of DataFrames from a list of DataFrames using List Comprehension (Pandas)

I have a list of DataFrames that have the same columns and different values. I want to drop some columns from the list of DataFrames in one line in pandas.

For far, I tried (dfs has list of Data Frames)

dfs.drop([col for col in ['var1', 'var2'] if col in dfs], axis=1, inplace=True)

and

dfs[dfs.drop([col for col in ['var1', 'var2'] if col in dfs], axis=1, inplace=True)]

both are giving same error:

AttributeError: 'list' object has no attribute 'drop'

type(dfs)
>> list

However, when i can loop through each DataFRame from the list dfs using for loop, I can drop the columns.

How can I do it in the list comprehension way in pandas?

like image 573
i.n.n.m Avatar asked Jul 19 '17 19:07

i.n.n.m


1 Answers

Assuming you want to drop ['var1', 'var2'] columns, and your data frames have the same columns, you should use a for loop.

for df in dfs:
    df.drop(['var1', 'var2'], axis=1, inplace=True)

Alternatively, you could also use this:

dfs = [df.drop(['var1', 'var2'], axis=1) for df in dfs]

Omitting the inplace=True will cause df.drop to return a new dataframe, rather than updating inplace and returning None.

like image 50
cs95 Avatar answered Nov 14 '22 23:11

cs95