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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With