简体   繁体   English

如何使用熊猫从Python中的txt文件计算属性(列)?

[英]How to count attributes (columns) from a txt file in Python using pandas?

I have a txt file that has rows and columns of data in it. 我有一个txt文件,其中包含数据的行和列。 I am trying to figure out how to count the number of columns (attributes) in the whole txt file. 我试图弄清楚如何计算整个txt文件中的列(属性)数。 Here is my code to read the txt file and to count the columns but it is giving me the wrong answer. 这是我的代码,用于读取txt文件并计算列数,但这给了我错误的答案。

    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)

len gives you all elements in the DataFrame (product of rows and columns). len为您提供DataFrame(行和列的乘积)中的所有元素。 The number of rows and columns are accessible with DataFrame.shape . 行数和列数可通过DataFrame.shape访问。 shape gives you a tuple where the first entry is the number of rows and the second the number of columns. shape为您提供一个元组,其中第一个条目是行数,第二个条目是列数。 So you can print the number of columns with: 因此,您可以使用以下命令打印列数:

print(data_file.shape[1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM