本教程为初学者提供Python数据分析库Pandas的基础知识讲解与实践操作指导,涵盖数据结构、基本函数及常用方法等内容。
### pandas基础使用教程知识点概述
#### 1. pandas.Series
`pandas.Series` 是一个一维数组对象,它能够保存任何数据类型(整型、字符串、浮点型等)。一个 `Series` 可以被看作是具有统一类型的数据数组,并且带有标签。
**参数解释**:
- `data`: 数据内容,可以是列表、字典或其他可迭代对象。
- `index`: 索引标签,默认为整数索引。
- `dtype`: 数据类型,默认自动推断。
- `name`: 名称,默认为 None。
- `copy`: 是否复制数据,默认为 False。
**示例**:
```python
# 默认索引从 0 开始
list_series = pd.Series([a, b, c])
print(list_series)
# 输出:
# 0 a
# 1 b
# 2 c
# dtype: object
# 自定义索引
list_series = pd.Series([Leslie, Jack, Mike], index=[2, 1, 3])
print(list_series)
# 输出:
# 2 Leslie
# 1 Jack
# 3 Mike
# dtype: object
# 通过字典创建 Series
list_series = pd.Series({2: Leslie, 1: Jack, 3: Mike})
print(list_series)
# 输出:
# 2 Leslie
# 1 Jack
# 3 Mike
# dtype: object
# 指定索引并筛选
list_series = pd.Series({2: Leslie, 1: Jack, 3: Mike}, index=[2, 3])
print(list_series)
# 输出:
# 2 Leslie
# 3 Mike
# dtype: object
# 指定列名
price = pd.Series([68, 90], name=price, index=[JAVA IN ACTION, Python Data Science Handbook])
print(price)
# 输出:
# JAVA IN ACTION 68
# Python Data Science Handbook 90
# Name: price, dtype: object
```
#### 2. pandas.DataFrame - 根据行建立数据
`DataFrame` 是一个表格型数据结构,它包含一组有序的列,每列可以是不同的值类型(例如整数、字符串、浮点数等)。DataFrame 的行和列都有标签。
**创建 DataFrame 方法**:
- 通过列表创建 DataFrame
- 通过字典创建 DataFrame
- 通过数据创建 DataFrame
**示例**:
```python
# 通过列表创建 DataFrame
df_list = pd.DataFrame([[1, 2], [3, 4]], columns=[A, B])
print(df_list)
# 输出:
# A B
# 0 1 2
# 1 3 4
# 通过字典创建 DataFrame
df_dict = pd.DataFrame({A: [1, 2], B: [3, 4]})
print(df_dict)
# 输出:
# A B
# 0 1 3
# 1 2 4
# 使用数据创建 DataFrame
data = {A: [1, 2], B: [3, 4]}
df_data = pd.DataFrame(data)
print(df_data)
# 输出:
# A B
# 0 1 3
# 1 2 4
```
#### 3. pandas.DataFrame - 根据列建立数据
通过提供一个字典,其中键作为列名,值作为对应的 Series 或者列表来构建 DataFrame。
**示例**:
```python
# 使用字典创建 DataFrame
df_dict = pd.DataFrame({A: [1, 2], B: [3, 4]})
print(df_dict)
# 输出:
# A B
# 0 1 3
# 1 2 4
```
#### 4. pandas.DataFrame - 根据数据建立列数据
通过提供一个列表,其中每个元素也是一个列表或元组,每个内部列表或元组代表 DataFrame 的一行来创建 DataFrame。
**示例**:
```python
df = pd.DataFrame([[1,2],[3,4]], columns=[A, B])
print(df)
# 输出:
# A B
# 0 1 2
# 1 3 4
```
#### 5. 利用索引和标签进行数据选择
DataFrame 允许通过行名或列名来访问特定的数据。
**示例**:
```python
df = pd.DataFrame({A: [1,2], B:[3,4]}, index=[row0, row1])
print(df)
# 输出:
# A B
# row0 1 3
# row