简体   繁体   English

使用python和csv的特定行的列数

[英]Number of columns for a specific row using python and csv

I want to get the exact number of colums for a given row of a csv file. 我想获取csv文件给定行的确切列数。 That means row x and x+1 could have different columns. 这意味着行x和x + 1可以具有不同的列。 Using this code: 使用此代码:

def num_columns(dir,y):
        f=dir+'\\data.csv'
        f=open(f, 'r')
        reader = csv.reader(f,delimiter=';')
        n=0
        for row in reader:
            if y==n:
                print(len(row))
                return len(row)
            n+=1

where y is the row and dir where the csv is located. 其中y是csv所在的行和目录。

The problem is that it returns the higher value of columns from the document. 问题在于它从文档中返回更高的列值。 Not the specific row. 没有特定的行。 That I don't understand, because I'm using "n" precisely to return once its on the row. 我不明白,因为我正好用“ n”返回它在行中的一次。 Thanks 谢谢

First read in your csv using: 首先使用以下命令在您的csv中阅读:

df = pd.read_csv('filename.csv')

Once the data is in a pandas dataframe the function below will return a series with the number of values in each row. 数据放入pandas数据框后,下面的函数将返回一个带有每行值数的序列。

df.apply(lambda x: x.count(), axis=1)

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

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