0

I have a txt file that has rows and columns of data in it. I am trying to figure out how to count the number of columns (attributes) in the whole txt file. Here is my code to read the txt file and to count the columns but it is giving me the wrong answer.

    import pandas as pd 

    data_file = pd.read_csv('3human_evolution.txt')
    data_file.columns = data_file.columns.str.strip()
    A=len(data_file.columns)
    print(A)
4
  • this line data_file.columns = data_file.columns.str.strip() - doesn't make much sense to me. If you have sep=',' (default), then why would you want to split columns by spaces/tabs? Can you provide a few first lines of your file? Commented Nov 28, 2017 at 17:28
  • not seeing how could possibly pandas give you the wrong count here? and strip() will only take out spaces from left and right most given there are any. on command line if you do df.columns it gives a list[str]. you should do no more than len(df.columns) to get the count here. what's the wrong answer you getting? what did you expect ? Commented Nov 28, 2017 at 17:54
  • if you can read the file using read_csv then you can get the number of rows and columns like this: print data_file.shape Commented Nov 28, 2017 at 17:55
  • It is printing that there is one column but really there are five. I am still not getting the correct answer even with what y'all are suggesting. Commented Nov 28, 2017 at 21:48

1 Answer 1

1

len gives you all elements in the DataFrame (product of rows and columns). The number of rows and columns are accessible with DataFrame.shape. shape gives you a tuple where the first entry is the number of rows and the second the number of columns. So you can print the number of columns with:

print(data_file.shape[1])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.