App下載

Python 如何讀取數(shù)據(jù):從入門到精通

養(yǎng)了一個閑月亮 2024-06-04 15:03:16 瀏覽數(shù) (617)
反饋

315646df51f00924b16e60c0b6a46868 (1)

Python 作為數(shù)據(jù)科學領(lǐng)域的熱門語言,其強大的數(shù)據(jù)讀取能力功不可沒。本文將帶你全面了解 Python 如何讀取數(shù)據(jù),從基礎(chǔ)的文件讀取到處理結(jié)構(gòu)化數(shù)據(jù),助你輕松開啟數(shù)據(jù)分析之旅。

一、讀取文本文件

文本文件是最常見的數(shù)據(jù)存儲格式之一,Python 提供了簡潔易用的方法讀取這類文件。

  • 打開文件:使用?open()?函數(shù)打開文件,并指定打開模式('r' 表示讀取,'w' 表示寫入,'a' 表示追加)。

file = open('data.txt', 'r')

  • 讀取內(nèi)容:使用?read()?方法讀取文件全部內(nèi)容,或使用?readline()?逐行讀取。

content = file.read()
print(content)

line = file.readline()
print(line)

  • 關(guān)閉文件:使用?close()?方法關(guān)閉文件,釋放資源。

file.close()

為了避免忘記關(guān)閉文件,推薦使用?with open()?語句,它會在代碼塊執(zhí)行完畢后自動關(guān)閉文件。

with open('data.txt', 'r') as file:
    content = file.read()
    print(content)

二、處理 CSV 文件

CSV (Comma-Separated Values) 是一種常用的結(jié)構(gòu)化數(shù)據(jù)存儲格式,Python 的?csv?模塊提供了便捷的處理方法。

  • 讀取 CSV 文件:使用?reader()?函數(shù)讀取 CSV 文件,返回一個可迭代的對象,每一行都是一個列表。

import csv

with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

  • 處理 CSV 數(shù)據(jù):可以根據(jù)需要對讀取到的數(shù)據(jù)進行處理,例如提取特定列、數(shù)據(jù)類型轉(zhuǎn)換等。

import csv

with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    next(reader)  # 跳過標題行
    for row in reader:
        name = row[0]
        age = int(row[1])
        print(f"Name: {name}, Age: {age}")

三、利用 Pandas 處理結(jié)構(gòu)化數(shù)據(jù)

Pandas 是 Python 數(shù)據(jù)分析領(lǐng)域的利器,它提供了 DataFrame 數(shù)據(jù)結(jié)構(gòu),能夠高效地處理結(jié)構(gòu)化數(shù)據(jù)。

  • 讀取數(shù)據(jù):Pandas 提供了?read_csv()?、?read_excel()?等函數(shù),可以方便地讀取不同格式的數(shù)據(jù)文件。

import pandas as pd

df = pd.read_csv('data.csv')
print(df)

  • 數(shù)據(jù)處理:Pandas 提供了豐富的函數(shù)和方法,可以進行數(shù)據(jù)篩選、排序、分組、統(tǒng)計分析等操作。

# 選擇年齡大于 30 的數(shù)據(jù)
df[df['Age'] > 30]

# 按年齡排序
df.sort_values(by='Age')

# 計算平均年齡
df['Age'].mean()

四、讀取 JSON 數(shù)據(jù)

JSON (JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式,Python 的?json?模塊可以方便地處理 JSON 數(shù)據(jù)。

  • 讀取 JSON 數(shù)據(jù):使用?load()?函數(shù)讀取 JSON 文件或字符串,返回一個 Python 字典或列表。

import json

with open('data.json', 'r') as file:
    data = json.load(file)
    print(data)

  • 訪問 JSON 數(shù)據(jù):可以像操作字典一樣訪問 JSON 數(shù)據(jù)。

name = data['name']
age = data['age']
print(f"Name: {name}, Age: {age}")

總結(jié)

本文介紹了 Python 讀取數(shù)據(jù)的常用方法,包括讀取文本文件、CSV 文件、JSON 數(shù)據(jù)以及利用 Pandas 處理結(jié)構(gòu)化數(shù)據(jù)。熟練掌握這些方法將為你進行數(shù)據(jù)分析打下堅實的基礎(chǔ)。


0 人點贊