2

I have multiple dataframes in a list CGdfs.

CGdfs = [CGdf_2002, CGdf_2003, CGdf_2004, CGdf_2005, CGdf_2006, CGdf_2007, CGdf_2008, CGdf_2009, CGdf_2010, CGdf_2011, CGdf_2012, CGdf_2013, CGdf_2014, CGdf_2015, CGdf_2016, CGdf_2017, CGdf_2018]

I want to drop a column named 'Plot' from all these dataframes using a loop. How do I do this?

I have tried the below, this does not work

for df in CGdfs:
   df = df.drop('Plot', axis =1)
4
  • 1
    Please explain why it does not work. Do you get errors? Post the traceback Commented May 23, 2019 at 15:12
  • Have you tried with del df["Plot"]? Commented May 23, 2019 at 15:13
  • @cs95 just asking-> how is df.pop('col_name') for loops ? Commented May 23, 2019 at 15:27
  • 1
    @anky_91 It does god's work - it removes a column but also returns it. Problem is you can only pop one at a time so it is limiting if you want to drop multiple columns. Commented May 23, 2019 at 15:28

2 Answers 2

1

This should work:

for df in CGdfs:
    df.drop(columns = ['Plot'], inplace= True)
Sign up to request clarification or add additional context in comments.

3 Comments

Both of them are wrong. Can you figure out why?
The first one does not appear to re-assign the new df(modified) to the df in the list. Second one seems to work(tested it out)
Yes! Removed the incorrect answer from your post.
1

I think the problem is that it's not applying the drop to the original DataFrame object. Try:

for df in CGdfs:
    df.drop('Plot', axis=1, inplace=True)

When you inspect the elements of CGdfs the "Plot" column should be removed.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.