Pandas中的DataFrame其實是由Series組成的

2024年2月6日 20点热度 0人点赞

在 Pandas 中,Series 和 DataFrame 是兩種最基本的數據結構,它們用於處理和分析數據。Pandas 是基於 NumPy 構建的,提供了更多功能和更方便的數據操作方法,特別適用於數據處理和分析任務。

Series

Series 是一種一維的數據結構,你可以將它想象成一個單列的數據表。每個 Series 都有一個唯一的索引(Index),可以通過這個索引訪問其中的數據。

主要特點

  1. 一維數據:Series 可以存儲任何數據類型(整數、字符串、浮點數、Python 對象等)。
  2. 可變性:Series 的大小是可變的,可以進行增加或刪除操作。
  3. 數據對齊:自動數據對齊功能是 Series 最重要的特性之一,尤其是在處理不同索引的數據時。
import pandas as pd
# 使用列表創建 Series
s = pd.Series([1, 2, 3, 4, 5])

DataFrame

DataFrame 是一種二維的表格型數據結構,是 Pandas 中最常用的數據結構。可以將 DataFrame 看作是由多個 Series 組成的字典(每個 Series 作為一個列)。

#pgc-card .pgc-card-href { text-decoration: none; outline: none; display: block; width: 100%; height: 100%; } #pgc-card .pgc-card-href:hover { text-decoration: none; } /*pc 樣式*/ .pgc-card { box-sizing: border-box; height: 164px; border: 1px solid #e8e8e8; position: relative; padding: 20px 94px 12px 180px; overflow: hidden; } .pgc-card::after { content: " "; display: block; border-left: 1px solid #e8e8e8; height: 120px; position: absolute; right: 76px; top: 20px; } .pgc-cover { position: absolute; width: 162px; height: 162px; top: 0; left: 0; background-size: cover; } .pgc-content { overflow: hidden; position: relative; top: 50%; -webkit-transform: translateY(-50%); transform: translateY(-50%); } .pgc-content-title { font-size: 18px; color: #222; line-height: 1; font-weight: bold; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .pgc-content-desc { font-size: 14px; color: #444; overflow: hidden; text-overflow: ellipsis; padding-top: 9px; overflow: hidden; line-height: 1.2em; display: -webkit-inline-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } .pgc-content-price { font-size: 22px; color: #f85959; padding-top: 18px; line-height: 1em; } .pgc-card-buy { width: 75px; position: absolute; right: 0; top: 50px; color: #406599; font-size: 14px; text-align: center; } .pgc-buy-text { padding-top: 10px; } .pgc-icon-buy { height: 23px; width: 20px; display: inline-block; background: url(https://lf6-cdn-tos.bytescm.com/obj/cdn-static-resource/pgc/v2/pgc_tpl/static/image/commodity_buy_f2b4d1a.png); }

主要特點

  1. 二維數據:可以存儲不同數據類型的列,例如整數、日期、浮點數和字符串。
  2. 大小可變:可以動態地調整尺寸,比如添加或刪除列。
  3. 標記軸(行和列):可以有行索引和列標簽。
  4. 可以進行算術運算:支持對行和列進行算術運算。
# 使用字典創建 DataFrame
df = pd.DataFrame({
    'A': [1, 2, 3],
    'B': [4, 5, 6],
    'C': [7, 8, 9]
})

Series 與 DataFrame 的關系

  • 每個 DataFrame 都是由多個 Series 構成的,這些 Series 共享同一個索引。
  • Series 可以被看作是 DataFrame 的一個單列。

用途

  • Series:適用於處理時間序列數據、各別列的數據處理等。
  • DataFrame:適用於處理多維度數據、執行復雜的數據分析任務、進行數據清洗和預處理等。

Pandas 的強大功能和靈活性使得 Series 和 DataFrame 成為 Python 數據分析的重要工具。