如何创建熊猫函数以读取不同大小的数据框

问题描述 投票:-1回答:2

我正在为我的工作自动执行里程旅行,这涉及读取.csv文件并使用pandas模块。问题是.csv文件的长度不同,因为每个人的行程都不同。是否有什么可以创建一个准确读取行程数的函数,而不管.csv文件的长度如何? .csv文件在行下面有一些多余的行,我不想读入DataFrame。

      a  b  c  
trip1 x  x  x  
trip2 x  x  x 
trip3 x  x  x  
      a  b  c  
trip1 x  x  x  
trip2 x  x  x 
trip3 x  x  x
trip4 x  x  x
      ...
trip9 x  x  x 
python pandas
2个回答
0
投票

如果要打印第一行,请使用df.head()

import pandas as pd

def read():
     df = df.read_csv('csv_file.csv')
     df.head(10) #depends how many rows you want to print.
     print(df)

如果要从底部开始打印,请使用df.tail()

import pandas as pd
def read():
    df = df.read_csv('csv_file.csv')
    df.tail(10) #depends how many rows you want to print.
    print(df)

0
投票

我假设您想从.csv文件中读取n行,您可以这样做:

pd.read_csv('path_to_file.csv', nrows=10)

这将仅读取csv中的前10行。如果要读取包含大量数据和大小的文件,这将很有帮助。

如果要跳过最后n行,可以执行以下操作:

pd.read_csv('path_to_file.csv', skipfooter=2)

这将始终跳过csv中的最后2行。

文档:https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html

© www.soinside.com 2019 - 2024. All rights reserved.