Pandas 基本功能怎么用?Python Pandas 新手入门操作详解?

文章导读
Previous Quiz Next Pandas 是 Python 中的一个强大数据操作库,提供处理 Series 和 DataFrame 格式数据的必需工具。这两种数据结构对于处理和分析大型数据集至关重要。
📋 目录
  1. 在 Pandas 中使用属性
  2. Pandas 中的基本方法探索
A A

Python Pandas - 基本功能



Previous
Quiz
Next

Pandas 是 Python 中的一个强大数据操作库,提供处理 Series 和 DataFrame 格式数据的必需工具。这两种数据结构对于处理和分析大型数据集至关重要。

理解 Pandas 的基本功能,包括其属性和方法,对于有效管理数据至关重要,这些属性和方法提供了关于数据的宝贵洞察,使其更容易理解和处理。在本教程中,您将学习 Pandas 中处理这些数据结构至关重要的基本属性和方法。

在 Pandas 中使用属性

Pandas 中的属性允许您访问关于 Series 和 DataFrame 对象的元数据。通过使用这些属性,您可以探索并轻松理解数据。

Series 和 DataFrame 属性

以下是 Series 和 DataFrame 对象中广泛使用的属性 −

序号 属性 & 描述
1

dtype

返回 Series 或 DataFrame 中元素的 data type。

2

index

提供 Series 或 DataFrame 的索引(行标签)。

3

values

以 NumPy array 的形式返回 Series 或 DataFrame 中的数据。

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

# 使用随机数创建 Series
s = pd.Series(np.random.randn(4))

# 探索属性
print("Series 的数据类型:", s.dtype)
print("Series 的索引:", s.index)
print("Series 的值:", s.values)
print("Series 的形状:", s.shape)
print("Series 的维度数:", s.ndim)
print("Series 的大小:", s.size)
print("Series 是否为空?:", 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

# 使用随机数创建 DataFrame
df = pd.DataFrame(np.random.randn(3, 4), columns=list('ABCD'))
print("DataFrame:")
print(df)

print("结果:")
print("数据类型:", df.dtypes)
print("索引:", df.index)
print("列:", df.columns)
print("值:")
print(df.values)
print("形状:", df.shape)
print("维度数:", df.ndim)
print("大小:", df.size)
print("是否为空:", 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 的简洁摘要,包括 index dtype 和 column dtypes、非空值以及内存使用情况。

4

describe()

生成 DataFrame 或 Series 的描述性统计信息,例如 count、mean、std、min 和 max。

示例

现在让我们创建一个 Series,并查看 Series 基本方法的运行情况。

import pandas as pd
import numpy as np

# 使用随机数创建一个 Series
s = pd.Series(np.random.randn(10))

print("Series:")
print(s)

# 使用基本方法
print("Series 的前 5 个元素:\n", s.head())
print("\nSeries 的最后 3 个元素:\n", s.tail(3))
print("\nSeries 的描述性统计信息:\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

# 创建一个 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])}
 
# 创建一个 DataFrame
df = pd.DataFrame(data)
print("我们的数据框是:\n")
print(df)

# 使用基本方法
print("\nDataFrame 的前 5 行:\n", df.head())
print("\nDataFrame 的最后 3 行:\n", df.tail(3))
print("\nDataFrame 的信息:")
df.info()
print("\nDataFrame 的描述性统计信息:\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