Comparing columns from two CSV files











up vote
1
down vote

favorite












This question has a second part here:



Comparing columns from two CSV files - follow-up



I'm currently trying to compare two CSV files column by column but only when their indexes match.



Here is what I've done:



import sys

def get_column(columns, name):
count = 0
columns = columns.split(';')
for column in columns:
array = list(column)
if(array[0] == '"'):
array[0] = ''
if(array[len(column) - 1] == '"'):
array[len(column) - 1] = ''
column = ''.join(array)
if column != name:
count += 1
else:
return(count)

def set_up_file(file, variable):
columns = next(file)
siren_pos = get_column(columns, 'INDEX1')
nic_pos = get_column(columns, 'INDEX2')
variable_pos = get_column(columns, variable)
return(siren_pos, nic_pos, variable_pos)

def test_variable(variable):
with open('source.csv', 'r') as source:
sir_s, nic_s, comp_s = set_up_file(source, variable)
with open('tested.csv', 'r') as tested:
sir_t, nic_t, comp_t = set_up_file(tested, variable)
correct = 0
memory = 0
for row_s in source:
row_s = row_s.split(';')
tested.seek(0, 0)
count = 0
for row_t in tested:
count += 1
if(count >= memory):
row_t = row_t.split(';')
if(row_s[sir_s] == row_t[sir_t] and row_s[nic_s] == row_t[nic_t]):
if(row_s[comp_s] == row_t[comp_t]):
correct += 1
memory = count
break
tested.seek(0, 0)
print(correct / sum(1 for line in tested) * 100)

def main():
test_variable('VARIABLE_TO_COMPARE')


if(__name__ == "__main__"):
main()


This script is running into some performance issue and I would like to know how to make it run faster / make it more readable.










share|improve this question




























    up vote
    1
    down vote

    favorite












    This question has a second part here:



    Comparing columns from two CSV files - follow-up



    I'm currently trying to compare two CSV files column by column but only when their indexes match.



    Here is what I've done:



    import sys

    def get_column(columns, name):
    count = 0
    columns = columns.split(';')
    for column in columns:
    array = list(column)
    if(array[0] == '"'):
    array[0] = ''
    if(array[len(column) - 1] == '"'):
    array[len(column) - 1] = ''
    column = ''.join(array)
    if column != name:
    count += 1
    else:
    return(count)

    def set_up_file(file, variable):
    columns = next(file)
    siren_pos = get_column(columns, 'INDEX1')
    nic_pos = get_column(columns, 'INDEX2')
    variable_pos = get_column(columns, variable)
    return(siren_pos, nic_pos, variable_pos)

    def test_variable(variable):
    with open('source.csv', 'r') as source:
    sir_s, nic_s, comp_s = set_up_file(source, variable)
    with open('tested.csv', 'r') as tested:
    sir_t, nic_t, comp_t = set_up_file(tested, variable)
    correct = 0
    memory = 0
    for row_s in source:
    row_s = row_s.split(';')
    tested.seek(0, 0)
    count = 0
    for row_t in tested:
    count += 1
    if(count >= memory):
    row_t = row_t.split(';')
    if(row_s[sir_s] == row_t[sir_t] and row_s[nic_s] == row_t[nic_t]):
    if(row_s[comp_s] == row_t[comp_t]):
    correct += 1
    memory = count
    break
    tested.seek(0, 0)
    print(correct / sum(1 for line in tested) * 100)

    def main():
    test_variable('VARIABLE_TO_COMPARE')


    if(__name__ == "__main__"):
    main()


    This script is running into some performance issue and I would like to know how to make it run faster / make it more readable.










    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      This question has a second part here:



      Comparing columns from two CSV files - follow-up



      I'm currently trying to compare two CSV files column by column but only when their indexes match.



      Here is what I've done:



      import sys

      def get_column(columns, name):
      count = 0
      columns = columns.split(';')
      for column in columns:
      array = list(column)
      if(array[0] == '"'):
      array[0] = ''
      if(array[len(column) - 1] == '"'):
      array[len(column) - 1] = ''
      column = ''.join(array)
      if column != name:
      count += 1
      else:
      return(count)

      def set_up_file(file, variable):
      columns = next(file)
      siren_pos = get_column(columns, 'INDEX1')
      nic_pos = get_column(columns, 'INDEX2')
      variable_pos = get_column(columns, variable)
      return(siren_pos, nic_pos, variable_pos)

      def test_variable(variable):
      with open('source.csv', 'r') as source:
      sir_s, nic_s, comp_s = set_up_file(source, variable)
      with open('tested.csv', 'r') as tested:
      sir_t, nic_t, comp_t = set_up_file(tested, variable)
      correct = 0
      memory = 0
      for row_s in source:
      row_s = row_s.split(';')
      tested.seek(0, 0)
      count = 0
      for row_t in tested:
      count += 1
      if(count >= memory):
      row_t = row_t.split(';')
      if(row_s[sir_s] == row_t[sir_t] and row_s[nic_s] == row_t[nic_t]):
      if(row_s[comp_s] == row_t[comp_t]):
      correct += 1
      memory = count
      break
      tested.seek(0, 0)
      print(correct / sum(1 for line in tested) * 100)

      def main():
      test_variable('VARIABLE_TO_COMPARE')


      if(__name__ == "__main__"):
      main()


      This script is running into some performance issue and I would like to know how to make it run faster / make it more readable.










      share|improve this question















      This question has a second part here:



      Comparing columns from two CSV files - follow-up



      I'm currently trying to compare two CSV files column by column but only when their indexes match.



      Here is what I've done:



      import sys

      def get_column(columns, name):
      count = 0
      columns = columns.split(';')
      for column in columns:
      array = list(column)
      if(array[0] == '"'):
      array[0] = ''
      if(array[len(column) - 1] == '"'):
      array[len(column) - 1] = ''
      column = ''.join(array)
      if column != name:
      count += 1
      else:
      return(count)

      def set_up_file(file, variable):
      columns = next(file)
      siren_pos = get_column(columns, 'INDEX1')
      nic_pos = get_column(columns, 'INDEX2')
      variable_pos = get_column(columns, variable)
      return(siren_pos, nic_pos, variable_pos)

      def test_variable(variable):
      with open('source.csv', 'r') as source:
      sir_s, nic_s, comp_s = set_up_file(source, variable)
      with open('tested.csv', 'r') as tested:
      sir_t, nic_t, comp_t = set_up_file(tested, variable)
      correct = 0
      memory = 0
      for row_s in source:
      row_s = row_s.split(';')
      tested.seek(0, 0)
      count = 0
      for row_t in tested:
      count += 1
      if(count >= memory):
      row_t = row_t.split(';')
      if(row_s[sir_s] == row_t[sir_t] and row_s[nic_s] == row_t[nic_t]):
      if(row_s[comp_s] == row_t[comp_t]):
      correct += 1
      memory = count
      break
      tested.seek(0, 0)
      print(correct / sum(1 for line in tested) * 100)

      def main():
      test_variable('VARIABLE_TO_COMPARE')


      if(__name__ == "__main__"):
      main()


      This script is running into some performance issue and I would like to know how to make it run faster / make it more readable.







      python csv






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 at 15:33









      Jamal

      30.2k11115226




      30.2k11115226










      asked Nov 21 at 13:48









      Comte_Zero

      6911




      6911






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          First I'd like to call out the good things that you've done:




          • Writing functions, including a standard main().

          • Having more or less sensible function and variable names.

          • Proper use of with.


          An improvement here is to stop parsing the file yourself, and to start parsing it with Python's native csv library. Even though your format is not technically CSV (it's separated by semicolon), you can still configure csv to use a different delimiter.



          I recommend the use of the DictReader class. Given that you only pay attention to one variable, just use csv.reader. During initialization, get the index of the column you want, and then use that on every record that the reader gives back.



          The critical performance issue here is that you have nested loops for row comparison. Given that you are comparing two series expected to be in the same order, but with edits (insertions and deletions), effectively you're doing a diff. Read this for a nice walkthrough.



          http://www.xmailserver.org/diff2.pdf






          share|improve this answer























          • Indeed, changing the separator allowed me to use the csv module. However I can't use zip because the files are not containing exactly the same lines so it won't line up correctly
            – Comte_Zero
            Nov 21 at 14:38










          • @Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?
            – Reinderien
            Nov 21 at 14:41










          • Same order, random insertions and deletions
            – Comte_Zero
            Nov 21 at 14:44










          • And are you checking all of the columns in both files, or only some of the columns?
            – Reinderien
            Nov 21 at 14:45










          • This may vary, that is why the main function contains only one, potentially copiable line
            – Comte_Zero
            Nov 21 at 14:47











          Your Answer





          StackExchange.ifUsing("editor", function () {
          return StackExchange.using("mathjaxEditing", function () {
          StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
          StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
          });
          });
          }, "mathjax-editing");

          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "196"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208144%2fcomparing-columns-from-two-csv-files%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote



          accepted










          First I'd like to call out the good things that you've done:




          • Writing functions, including a standard main().

          • Having more or less sensible function and variable names.

          • Proper use of with.


          An improvement here is to stop parsing the file yourself, and to start parsing it with Python's native csv library. Even though your format is not technically CSV (it's separated by semicolon), you can still configure csv to use a different delimiter.



          I recommend the use of the DictReader class. Given that you only pay attention to one variable, just use csv.reader. During initialization, get the index of the column you want, and then use that on every record that the reader gives back.



          The critical performance issue here is that you have nested loops for row comparison. Given that you are comparing two series expected to be in the same order, but with edits (insertions and deletions), effectively you're doing a diff. Read this for a nice walkthrough.



          http://www.xmailserver.org/diff2.pdf






          share|improve this answer























          • Indeed, changing the separator allowed me to use the csv module. However I can't use zip because the files are not containing exactly the same lines so it won't line up correctly
            – Comte_Zero
            Nov 21 at 14:38










          • @Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?
            – Reinderien
            Nov 21 at 14:41










          • Same order, random insertions and deletions
            – Comte_Zero
            Nov 21 at 14:44










          • And are you checking all of the columns in both files, or only some of the columns?
            – Reinderien
            Nov 21 at 14:45










          • This may vary, that is why the main function contains only one, potentially copiable line
            – Comte_Zero
            Nov 21 at 14:47















          up vote
          2
          down vote



          accepted










          First I'd like to call out the good things that you've done:




          • Writing functions, including a standard main().

          • Having more or less sensible function and variable names.

          • Proper use of with.


          An improvement here is to stop parsing the file yourself, and to start parsing it with Python's native csv library. Even though your format is not technically CSV (it's separated by semicolon), you can still configure csv to use a different delimiter.



          I recommend the use of the DictReader class. Given that you only pay attention to one variable, just use csv.reader. During initialization, get the index of the column you want, and then use that on every record that the reader gives back.



          The critical performance issue here is that you have nested loops for row comparison. Given that you are comparing two series expected to be in the same order, but with edits (insertions and deletions), effectively you're doing a diff. Read this for a nice walkthrough.



          http://www.xmailserver.org/diff2.pdf






          share|improve this answer























          • Indeed, changing the separator allowed me to use the csv module. However I can't use zip because the files are not containing exactly the same lines so it won't line up correctly
            – Comte_Zero
            Nov 21 at 14:38










          • @Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?
            – Reinderien
            Nov 21 at 14:41










          • Same order, random insertions and deletions
            – Comte_Zero
            Nov 21 at 14:44










          • And are you checking all of the columns in both files, or only some of the columns?
            – Reinderien
            Nov 21 at 14:45










          • This may vary, that is why the main function contains only one, potentially copiable line
            – Comte_Zero
            Nov 21 at 14:47













          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          First I'd like to call out the good things that you've done:




          • Writing functions, including a standard main().

          • Having more or less sensible function and variable names.

          • Proper use of with.


          An improvement here is to stop parsing the file yourself, and to start parsing it with Python's native csv library. Even though your format is not technically CSV (it's separated by semicolon), you can still configure csv to use a different delimiter.



          I recommend the use of the DictReader class. Given that you only pay attention to one variable, just use csv.reader. During initialization, get the index of the column you want, and then use that on every record that the reader gives back.



          The critical performance issue here is that you have nested loops for row comparison. Given that you are comparing two series expected to be in the same order, but with edits (insertions and deletions), effectively you're doing a diff. Read this for a nice walkthrough.



          http://www.xmailserver.org/diff2.pdf






          share|improve this answer














          First I'd like to call out the good things that you've done:




          • Writing functions, including a standard main().

          • Having more or less sensible function and variable names.

          • Proper use of with.


          An improvement here is to stop parsing the file yourself, and to start parsing it with Python's native csv library. Even though your format is not technically CSV (it's separated by semicolon), you can still configure csv to use a different delimiter.



          I recommend the use of the DictReader class. Given that you only pay attention to one variable, just use csv.reader. During initialization, get the index of the column you want, and then use that on every record that the reader gives back.



          The critical performance issue here is that you have nested loops for row comparison. Given that you are comparing two series expected to be in the same order, but with edits (insertions and deletions), effectively you're doing a diff. Read this for a nice walkthrough.



          http://www.xmailserver.org/diff2.pdf







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 21 at 14:58

























          answered Nov 21 at 14:07









          Reinderien

          1,472616




          1,472616












          • Indeed, changing the separator allowed me to use the csv module. However I can't use zip because the files are not containing exactly the same lines so it won't line up correctly
            – Comte_Zero
            Nov 21 at 14:38










          • @Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?
            – Reinderien
            Nov 21 at 14:41










          • Same order, random insertions and deletions
            – Comte_Zero
            Nov 21 at 14:44










          • And are you checking all of the columns in both files, or only some of the columns?
            – Reinderien
            Nov 21 at 14:45










          • This may vary, that is why the main function contains only one, potentially copiable line
            – Comte_Zero
            Nov 21 at 14:47


















          • Indeed, changing the separator allowed me to use the csv module. However I can't use zip because the files are not containing exactly the same lines so it won't line up correctly
            – Comte_Zero
            Nov 21 at 14:38










          • @Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?
            – Reinderien
            Nov 21 at 14:41










          • Same order, random insertions and deletions
            – Comte_Zero
            Nov 21 at 14:44










          • And are you checking all of the columns in both files, or only some of the columns?
            – Reinderien
            Nov 21 at 14:45










          • This may vary, that is why the main function contains only one, potentially copiable line
            – Comte_Zero
            Nov 21 at 14:47
















          Indeed, changing the separator allowed me to use the csv module. However I can't use zip because the files are not containing exactly the same lines so it won't line up correctly
          – Comte_Zero
          Nov 21 at 14:38




          Indeed, changing the separator allowed me to use the csv module. However I can't use zip because the files are not containing exactly the same lines so it won't line up correctly
          – Comte_Zero
          Nov 21 at 14:38












          @Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?
          – Reinderien
          Nov 21 at 14:41




          @Comte_Zero Are both in the same order, with some random insertions and deletions? Or are the files the same size, but out of order with respect to each other?
          – Reinderien
          Nov 21 at 14:41












          Same order, random insertions and deletions
          – Comte_Zero
          Nov 21 at 14:44




          Same order, random insertions and deletions
          – Comte_Zero
          Nov 21 at 14:44












          And are you checking all of the columns in both files, or only some of the columns?
          – Reinderien
          Nov 21 at 14:45




          And are you checking all of the columns in both files, or only some of the columns?
          – Reinderien
          Nov 21 at 14:45












          This may vary, that is why the main function contains only one, potentially copiable line
          – Comte_Zero
          Nov 21 at 14:47




          This may vary, that is why the main function contains only one, potentially copiable line
          – Comte_Zero
          Nov 21 at 14:47


















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Code Review Stack Exchange!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          Use MathJax to format equations. MathJax reference.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208144%2fcomparing-columns-from-two-csv-files%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Список кардиналов, возведённых папой римским Каликстом III

          Deduzione

          Mysql.sock missing - “Can't connect to local MySQL server through socket”