如何在Python中計算CSV檔案的行數?


Python 是一種流行的程式語言,廣泛用於資料分析和科學計算。它提供了大量的庫和工具,使資料處理和分析更簡單、更快。Pandas 就是這樣一個庫,它建立在 NumPy 之上,為 Python 提供易於使用的資料結構和資料分析工具。

在本教程中,我們將探討如何使用 Python 和 Pandas 庫來計算 CSV 檔案的行數。計算 CSV 檔案的行數是資料分析和機器學習任務中常見的操作。透過使用 Pandas,我們可以輕鬆地將 CSV 檔案讀取到 DataFrame 物件中,然後使用 shape 屬性或 len() 函式來計算檔案中的行數。在文章的下一節中,我們將逐步介紹如何使用 Pandas 讀取 CSV 檔案,然後演示如何使用各種方法計算檔案中的行數。

如何在Python中計算CSV檔案的行數?

我們將使用 Python 3 和 Pandas 庫來計算 CSV 檔案的行數。

在開始之前,請確保您的系統上已安裝 Python 和 Pandas。如果您沒有安裝 Pandas,可以使用 pip(Python 的包安裝程式)安裝它。

開啟您的命令提示符(在 Windows 上)或終端(在 Linux/macOS 上),然後鍵入以下命令:

pip install pandas

上述命令將下載並安裝 Pandas 庫到您的系統。

安裝 Pandas 庫後,我們可以使用 import 語句將其匯入到我們的 Python 程式碼中。以下是如何匯入 Pandas 的示例:

import pandas as pd

在上面的程式碼中,我們匯入了 Pandas 庫,並將其簡稱為 pd,這是一種在 Python 程式設計中常用的約定。現在我們已經匯入了 Pandas,就可以在我們的程式碼中使用它的函式和類來計算 CSV 檔案的行數了。

我們將使用 Pandas 的 read_csv() 方法將 CSV 檔案讀取到 DataFrame 物件中。DataFrame 物件是一個二維表格型資料結構,通常用於資料分析和處理任務。

要使用 Pandas 讀取 CSV 檔案,可以使用以下程式碼片段:

import pandas as pd

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

在上面的程式碼示例中,我們使用 Pandas 的 read_csv() 方法讀取名為 sample.csv 的 CSV 檔案。這將返回一個包含 CSV 檔案資料的 DataFrame 物件。df 變數用於儲存此 DataFrame 物件。

Pandas 提供了兩種簡單的方法來計算 DataFrame 物件中的行數:使用 shape 屬性和 len() 函式。

使用 DataFrame Shape 屬性

DataFrame 物件的 shape 屬性可用於獲取 DataFrame 中的行數和列數。由於 DataFrame 中的行數對應於 CSV 檔案中的行數,因此我們可以使用 shape 屬性元組的第一個元素來獲取 CSV 檔案中的行數。

示例

# Import the pandas library as pd
import pandas as pd

# Read the CSV file into a pandas DataFrame object
df = pd.read_csv('filename.csv')


# Get the number of rows in the DataFrame, which is equal to the number of lines in the CSV file
num_lines = df.shape[0]

# Print the number of lines in the CSV file
print("Number of lines in the CSV file: ", num_lines)

在上面的程式碼中,我們使用 DataFrame 物件的 shape 屬性來獲取 DataFrame 中的行數,這對應於 CSV 檔案中的行數。然後我們將此值儲存在 num_lines 變數中並將其列印到控制檯。上面程式碼片段的輸出將類似於:

輸出

Number of lines in the CSV file:  10

現在我們知道了如何使用 DataFrame shape 屬性在 python 中計算 CSV 檔案的行數,讓我們繼續學習 len() 方法。

使用 len() 函式

或者,我們也可以使用內建的 len() 函式來計算 DataFrame 中的行數,這同樣對應於 CSV 檔案中的行數。

示例

# Import the pandas library as pd
import pandas as pd

# Read the CSV file into a pandas DataFrame object
df = pd.read_csv('filename.csv')

# Count the number of rows in the DataFrame object using the built-in len() function
num_lines = len(df)

# Print the number of lines in the CSV file
print("Number of lines in the CSV file: ", num_lines)

在上面的程式碼片段中,我們使用 len() 函式來獲取 DataFrame 中的行數,這同樣對應於 CSV 檔案中的行數。然後我們將此值儲存在 num_lines 變數中並將其列印到終端。同樣,上面程式碼的輸出將類似於:

輸出

Number of lines in the CSV file:  10

結論

在本教程中,我們學習瞭如何使用 Python 和 Pandas 庫來計算 CSV 檔案的行數。我們提供了兩種方法的示例:使用 DataFrame shape 屬性和使用內建的 len() 函式。透過使用 Pandas,我們可以輕鬆地將 CSV 檔案讀取到 DataFrame 物件中,然後使用 shape 屬性或 len() 函式來計算檔案中的行數。我們還為每種方法提供了一個可執行的程式碼示例,以便您更容易理解。

更新於:2023年7月24日

12K+ 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.