Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 903859
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T15:57:21+00:00 2026-05-15T15:57:21+00:00

i have the following code… reader=csv.DictReader(open(test1.csv,r)) allrows = list(reader) keepcols = [c for c

  • 0

i have the following code…

reader=csv.DictReader(open("test1.csv","r"))
allrows = list(reader)

keepcols = [c for c in allrows[0] if all(r[c] != '0' for r in allrows)]

print keepcols
writer=csv.DictWriter(open("output1.csv","w"),fieldnames='keepcols',extrasaction='ignore')
writer.writerows(allrows)

i have a csv file which has about 45 cols..
the first column has some names..
except the first column, all others have only 0’s and 1’s…
and of course, the whole table has some titles as well..
i m trying to read columns from csv file and i need to extract only those cols with 1’s
the problem is the output file is empty even though there are a few columns in the table with 1’s..

could somebody please help me out…. 🙁 i m stuck terribly..

Title    3003_contact    3003_backbone   3003_sidechain  3003_polar  3003_hydrophobic    3003_acceptor   3003_donor  3003_aromatic
l1  1   1   0   1   1   0   0   0
l1  1   0   1   0   0   0   1   0
l1  1   0   0   0   0   0   0   0
l1  1   0   0   0   1   0   0   1
l1  1   0   0   0   0   0   0   0
l2  1   0   0   0   1   0   0   0
l2  1   0   0   0   0   1   0   0
l3  1   0   0   0   0   0   0   0
l3  1   0   0   0   0   0   1   0
l3  1   0   0   0   0   0   0   1
l3  1   0   0   0   0   0   0   0
l3  1   0   0   0   0   0   0   0
l4  1   0   0   0   0   0   0   0
l4  1   0   0   0   0   0   0   0
l4  1   0   0   0   0   0   0   0

it returns only column 1… I’ve tried changing ‘keepcols’ to keepcols… and I get column2 first and then column1 as output

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T15:57:22+00:00Added an answer on May 15, 2026 at 3:57 pm

    Edit: If the input file is a comma-separated values file, then
    to maintain the order of the keys, use reader.fieldnames instead of the keys in allrows[0].

    So the solution would be:

    keepcols = [c for c in reader.fieldnames if any(r[c] != '0' for r in allrows)]
    

    The input file posted above looks like it has space-separated columns. In this case, I don’t think csv is the right tool for parsing it. Instead, you can use split:

    import csv
    with open("test1.csv","r") as f:
        fields=next(f).split()
        # print(fields)
        allrows=[]
        for line in f:
            line=line.split()
            row=dict(zip(fields,line))
            allrows.append(row)
            # print(row)
        keepcols = [c for c in fields if any(row[c] != '0' for row in allrows)]
        print keepcols
        writer=csv.DictWriter(open("output1.csv","w"),fieldnames=keepcols,extrasaction='ignore')
        writer.writerows(allrows)
    

    Edit2: The reason why the column order was changing is because for c in allrows[0] returns the keys of allrows[0] in an unspecified order. dict keys are not ordered by default. The above code works around this by defining fields to be a list, not a dict.

    Original answer:
    Change fieldnames='keepcols' to fieldnames=keepcols.

    fieldnames needs to be a sequence of keys, such as ['fieldA','fieldB',...].

    A potential pitfall to be aware of in Python is that strings are sequences. When you iterate over a string, you get the characters of the string. So when you say fieldnames='keepcols', you are setting fieldnames to be the sequence of characters ['k','e','e','p','c','o','l','s']. You don’t get an error because this is a valid sequence of keys. But your list of dicts, allrows doesn’t happen to have these keys. writer.writerows blithely ignores this since extrasaction='ignore'.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 490k
  • Answers 490k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I think Turbogears suffers a bit from being a little… May 16, 2026 at 9:55 am
  • Editorial Team
    Editorial Team added an answer HTML: <input type="text" name="name" id="uniqueID" value="value" /> JS: var nameValue… May 16, 2026 at 9:55 am
  • Editorial Team
    Editorial Team added an answer Look at the HTML source code. Open the page in… May 16, 2026 at 9:55 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

I Have following code: Controller: public ActionResult Step1() { return View(); } [AcceptVerbs(HttpVerbs.Post)] public
I have following Code Block Which I tried to optimize in the Optimized section
I have following code in html: <div> <div style=float:left;margin:0.5em> <span class=title>Label1</span><br/> <input type=text name=name1
I have following code import sys from ctypes import * from ctypes.util import find_library
I have following code: Tools::Logger.Log(string(GetLastError()), Error); GetLastError() returns a DWORD a numeric value, but
I have following code in VS2008 If Linq.Enumerable.Contains(Of String)(selectedUsersRoles, RoleCheckBox.Text) Then RoleCheckBox.Checked = True
I have following code in page load Protected Sub Page_Load(ByVal sender As Object, ByVal
I have following code in my Application. tmp=[[UILabel alloc] initWithFrame:label1Frame]; tmp.tag=1; tmp.textColor=[UIColor blackColor]; [tmp
I have the following code in my microcontroller project: if (newThrottle < currentThrottle) {
I have the following code; $.ajax({ url: /Home/jQueryAddComment, type: POST, dataType: json, data: json,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.