Python Pandas - 基本功能



Pandas 是 Python 中一個強大的資料操作庫,提供用於處理 Series 和 DataFrame 格式資料的必要工具。這兩種資料結構對於處理和分析大型資料集至關重要。

瞭解 Pandas 的基本功能,包括其屬性和方法,對於有效地管理資料至關重要,這些屬性和方法提供了對資料的寶貴見解,使理解和處理資料變得更容易。在本教程中,您將學習 Pandas 中一些基本屬性和方法,這些屬性和方法對於使用這些資料結構至關重要。

使用 Pandas 中的屬性

Pandas 中的屬性允許您訪問有關 Series 和 DataFrame 物件的元資料。透過使用這些屬性,您可以探索並輕鬆理解資料。

Series 和 DataFrame 屬性

以下是 Series 和 DataFrame 物件中廣泛使用的屬性:

序號 屬性和描述
1

dtype

返回 Series 或 DataFrame 中元素的資料型別。

2

index

提供 Series 或 DataFrame 的索引(行標籤)。

3

values

將 Series 或 DataFrame 中的資料作為 NumPy 陣列返回。

4

shape

返回一個元組,表示 DataFrame 的維度(行,列)。

5

ndim

返回物件的維度數。Series 始終是 1D,DataFrame 是 2D。

6

size

給出物件中元素的總數。

7

empty

檢查物件是否為空,如果為空則返回 True。

8

columns

提供 DataFrame 物件的列標籤。

示例

讓我們建立一個 Pandas Series 並探索這些屬性操作。

import pandas as pd
import numpy as np

# Create a Series with random numbers
s = pd.Series(np.random.randn(4))

# Exploring attributes
print("Data type of Series:", s.dtype)
print("Index of Series:", s.index)
print("Values of Series:", s.values)
print("Shape of Series:", s.shape)
print("Number of dimensions of Series:", s.ndim)
print("Size of Series:", s.size)
print("Is Series empty?:", s.empty)

輸出如下:

Data type of Series: float64
Index of Series: RangeIndex(start=0, stop=4, step=1)
Values of Series: [-1.02016329  1.40840089  1.36293022  1.33091391]
Shape of Series: (4,)
Number of dimensions of Series: 1
Size of Series: 4
Is Series empty?: False

示例

讓我們看看下面的示例,並瞭解這些屬性在 DataFrame 物件上的工作原理。

import pandas as pd
import numpy as np

# Create a DataFrame with random numbers
df = pd.DataFrame(np.random.randn(3, 4), columns=list('ABCD'))
print("DataFrame:")
print(df)

print("Results:")
print("Data types:", df.dtypes)
print("Index:", df.index)
print("Columns:", df.columns)
print("Values:")
print(df.values)
print("Shape:", df.shape)
print("Number of dimensions:", df.ndim)
print("Size:", df.size)
print("Is empty:", df.empty)

執行上述程式碼後,您將獲得以下輸出:

DataFrame:
          A         B         C         D
0  2.161209 -1.671807 -1.020421 -0.287065
1  0.308136 -0.592368 -0.183193  1.354921
2 -0.963498 -1.768054 -0.395023 -2.454112

Results:
Data types: 
A    float64
B    float64
C    float64
D    float64
dtype: object
Index: RangeIndex(start=0, stop=3, step=1)
Columns: Index(['A', 'B', 'C', 'D'], dtype='object')
Values:
[[ 2.16120893 -1.67180742 -1.02042138 -0.28706468]
 [ 0.30813618 -0.59236786 -0.18319262  1.35492058]
 [-0.96349817 -1.76805364 -0.3950226  -2.45411245]]
Shape: (3, 4)
Number of dimensions: 2
Size: 12
Is empty: False

探索 Pandas 中的基本方法

Pandas 在這兩種資料結構中都提供了多種基本方法,這使得輕鬆快速檢視和理解資料變得容易。這些方法幫助您獲得摘要並探索詳細資訊,而無需花費太多精力。

Series 和 DataFrame 方法

序號 方法和描述
1

head(n)

返回物件的前 n 行。n 的預設值為 5。

2

tail(n)

返回物件的後 n 行。n 的預設值為 5。

3

info()

提供 DataFrame 的簡潔摘要,包括索引 dtype 和列 dtype、非空值以及記憶體使用情況。

4

describe()

生成 DataFrame 或 Series 的描述性統計資訊,例如計數、均值、標準差、最小值和最大值。

示例

現在讓我們建立一個 Series 並檢視 Series 基本方法的工作原理。

import pandas as pd
import numpy as np

# Create a Series with random numbers
s = pd.Series(np.random.randn(10))

print("Series:")
print(s)

# Using basic methods
print("First 5 elements of the Series:\n", s.head())
print("\nLast 3 elements of the Series:\n", s.tail(3))
print("\nDescriptive statistics of the Series:\n", s.describe())

輸出如下:

Series:
0   -0.295898
1   -0.786081
2   -1.189834
3   -0.410830
4   -0.997866
5    0.084868
6    0.736541
7    0.133949
8    1.023674
9    0.669520
dtype: float64
First 5 elements of the Series:
 0   -0.295898
1   -0.786081
2   -1.189834
3   -0.410830
4   -0.997866
dtype: float64

Last 3 elements of the Series:
 7    0.133949
8    1.023674
9    0.669520
dtype: float64

Descriptive statistics of the Series:
 count    10.000000
mean     -0.103196
std       0.763254
min      -1.189834
25%      -0.692268
50%      -0.105515
75%       0.535627
max       1.023674
dtype: float64

示例

現在看看下面的示例,並瞭解基本方法在 DataFrame 物件上的工作原理。

import pandas as pd
import numpy as np

#Create a Dictionary of series
data = {'Name':pd.Series(['Tom','James','Ricky','Vin','Steve','Smith','Jack']),
   'Age':pd.Series([25,26,25,23,30,29,23]), 
   'Rating':pd.Series([4.23,3.24,3.98,2.56,3.20,4.6,3.8])}
 
#Create a DataFrame
df = pd.DataFrame(data)
print("Our data frame is:\n")
print(df)

# Using basic methods
print("\nFirst 5 rows of the DataFrame:\n", df.head())
print("\nLast 3 rows of the DataFrame:\n", df.tail(3))
print("\nInfo of the DataFrame:")
df.info()
print("\nDescriptive statistics of the DataFrame:\n", df.describe())

執行上述程式碼後,您將獲得以下輸出:

Our data frame is:

    Name  Age  Rating
0    Tom   25    4.23
1  James   26    3.24
2  Ricky   25    3.98
3    Vin   23    2.56
4  Steve   30    3.20
5  Smith   29    4.60
6   Jack   23    3.80

First 5 rows of the DataFrame:
     Name  Age  Rating
0    Tom   25    4.23
1  James   26    3.24
2  Ricky   25    3.98
3    Vin   23    2.56
4  Steve   30    3.20

Last 3 rows of the DataFrame:
     Name  Age  Rating
4  Steve   30     3.2
5  Smith   29     4.6
6   Jack   23     3.8

Info of the DataFrame:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 7 entries, 0 to 6
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   Name    7 non-null      object 
 1   Age     7 non-null      int64  
 2   Rating  7 non-null      float64
dtypes: float64(1), int64(1), object(1)
memory usage: 296.0+ bytes

Descriptive statistics of the DataFrame:
              Age    Rating
count   7.000000  7.000000
mean   25.857143  3.658571
std     2.734262  0.698628
min    23.000000  2.560000
25%    24.000000  3.220000
50%    25.000000  3.800000
75%    27.500000  4.105000
max    30.000000  4.600000
廣告