<think>我们根据用户提供的引用内容,结合Pandas DataFrame的常用操作,详细说明DataFrame的使用方法。以下内容将涵盖创建DataFrame、查看属性、数据选择、数据处理、迭代列等操作。
### 1. 创建DataFrame
DataFrame是Pandas中最常用的数据结构,它是一个二维表格数据结构,可以存储多种类型的数据,并具有行索引和列索引。
#### 1.1 使用二维列表创建
可以通过二维列表创建DataFrame,并指定列名(`columns`)和行索引(`index`)[^2]:
```python
import pandas as pd
import numpy as np
# 使用二维列表创建
data_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
df = pd.DataFrame(data_list, columns=['one', 'two', 'three'])
print(df)
```
#### 1.2 使用字典创建
字典的键将作为列名,值作为列数据(可以是列表、数组等):
```python
# 使用字典创建
data_dict = {
'name': ['Tom', 'Jone', 'Marry'],
'age': [20, 18, 19],
'income': [1000, 3000, 2000]
}
df1 = pd.DataFrame(data_dict)
print(df1)
```
#### 1.3 指定行索引
在创建时可以通过`index`参数指定行索引:
```python
df_indexed = pd.DataFrame(data_dict, index=['a', 'b', 'c'])
print(df_indexed)
```
#### 1.4 添加行或列
- **添加列**:直接为新列赋值
```python
df1['gender'] = ['M', 'F', 'F'] # 添加新列
```
- **添加行**:使用`loc`索引器
```python
df1.loc[3] = ['David', 22, 2500, 'M'] # 添加一行
```
### 2. 查看DataFrame属性
创建DataFrame后,可以查看其基本属性[^4]:
```python
print(df1.index) # 行索引
print(df1.columns) # 列索引
print(df1.values) # 值(二维数组形式)
print(df1.shape) # 形状(行数,列数)
print(df1.dtypes) # 每列的数据类型
print(df1.info()) # 详细信息(包括内存占用、非空值统计等)
```
### 3. 数据选择与切片
#### 3.1 选择列
- 选择单列:返回Series
```python
ages = df1['age'] # 或 df1.age
```
- 选择多列:返回DataFrame
```python
subset = df1[['name', 'age']]
```
#### 3.2 选择行
- 通过行索引标签选择:`loc`
```python
row_a = df1.loc['a'] # 选择索引为'a'的行
```
- 通过整数位置选择:`iloc`
```python
first_row = df1.iloc[0] # 第一行
```
- 切片选择多行:
```python
first_two = df1.iloc[0:2] # 前两行
```
#### 3.3 条件选择
使用布尔索引进行条件筛选:
```python
# 选择年龄大于18的行
adults = df1[df1['age'] > 18]
```
### 4. 数据处理
#### 4.1 数据运算
DataFrame支持向量化运算(基于列):
```python
df1['income_after_tax'] = df1['income'] * 0.9 # 新增一列,计算税后收入
```
#### 4.2 混合运算(DataFrame与Series)
默认情况下,Series的索引匹配DataFrame的列索引,然后进行行广播[^5]:
```python
# 创建一个Series,索引与DataFrame列名匹配
s = pd.Series([0.1, 0.2, 0.3], index=['age', 'income', 'income_after_tax'])
# 将DataFrame的每一行乘以Series(按列匹配)
result = df1[['age','income','income_after_tax']].mul(s, axis=1)
```
#### 4.3 缺失值处理
- 删除缺失值:
```python
df_cleaned = df1.dropna() # 删除包含NaN的行
```
- 填充缺失值:
```python
df_filled = df1.fillna(0) # 用0填充NaN
```
### 5. 迭代DataFrame
#### 5.1 迭代列
通过`columns`属性获取列名列表,然后迭代每一列[^3]:
```python
for column in df1.columns:
col_data = df1[column] # 获取列数据(Series)
print(column)
print(col_data.head()) # 打印前几行
```
#### 5.2 迭代行
使用`iterrows()`方法(效率较低,不推荐用于大数据):
```python
for index, row in df1.iterrows():
print(f"Index: {index}, Name: {row['name']}")
```
### 6. 数据分组与聚合
分组统计是数据分析中的常见操作:
```python
# 按性别分组,计算平均年龄和收入
grouped = df1.groupby('gender').agg({
'age': 'mean',
'income': ['min', 'max', 'mean']
})
print(grouped)
```
### 7. 数据可视化
Pandas内置了基于Matplotlib的绘图功能:
```python
df1.plot(kind='bar', x='name', y='income')
plt.title('Income by Name')
plt.show()
```
### 总结
本教程详细介绍了Pandas DataFrame的创建、属性查看、数据选择、处理、迭代和可视化等操作。通过灵活运用这些功能,可以高效处理和分析结构化数据。更多高级功能请参考[Pandas官方文档](https://pandas.pydata.org/docs/)。
§§相关问题§§
1. 如何在DataFrame中处理时间序列数据?
2. DataFrame的`groupby`操作有哪些高级用法?
3. 如何优化Pandas处理大型DataFrame的性能?
4. DataFrame与SQL数据库如何交互?
5. 如何将DataFrame数据导出到Excel并设置格式?</think>### Pandas DataFrame 详细使用指南
DataFrame 是 Pandas 的核心数据结构,代表二维表格数据(类似 Excel 表格)。以下是详细使用方法:
#### 1. 创建 DataFrame
**方法 1:从字典创建**(最常用)
```python
import pandas as pd
data = {
'姓名': ['张三', '李四', '王五'],
'年龄': [25, 30, 28],
'城市': ['北京', '上海', '广州']
}
df = pd.DataFrame(data)
print(df)
```
输出:
```
姓名 年龄 城市
0 张三 25 北京
1 李四 30 上海
2 王五 28 广州
```
**方法 2:从二维列表创建**
```python
data_list = [
['张三', 25, '北京'],
['李四', 30, '上海'],
['王五', 28, '广州']
]
df = pd.DataFrame(data_list, columns=['姓名', '年龄', '城市'])
```
**方法 3:从 NumPy 数组创建**
```python
import numpy as np
arr = np.array([[1, 2], [3, 4], [5, 6]])
df = pd.DataFrame(arr, columns=['列1', '列2'])
```
#### 2. 查看 DataFrame 属性
```python
print(df.index) # 行索引
print(df.columns) # 列索引
print(df.shape) # 维度 (行数, 列数)
print(df.dtypes) # 每列数据类型
print(df.values) # 原始数据值(二维数组)[^4]
```
#### 3. 数据选择与切片
**选择列**:
```python
# 单列(返回 Series)
ages = df['年龄']
# 多列(返回 DataFrame)
subset = df[['姓名', '城市']]
```
**选择行**:
```python
# 按位置选择
row1 = df.iloc[0] # 第一行
rows_1to2 = df.iloc[0:2] # 切片
# 按索引选择
df.set_index('姓名', inplace=True) # 设置姓名为索引
row_zhangsan = df.loc['张三'] # 通过索引值选择
```
**条件筛选**:
```python
# 筛选年龄大于28的记录
result = df[df['年龄'] > 28]
# 多条件筛选
result = df[(df['年龄'] > 25) & (df['城市'] == '上海')]
```
#### 4. 数据处理
**添加/删除列**:
```python
# 添加新列
df['收入'] = [8000, 12000, 10000]
# 删除列
df.drop('收入', axis=1, inplace=True)
```
**处理缺失值**:
```python
# 检测缺失值
print(df.isnull())
# 填充缺失值
df.fillna(0, inplace=True) # 用0填充
# 删除含缺失值的行
df.dropna(inplace=True)
```
**数据运算**:
```python
# 列运算
df['税后收入'] = df['收入'] * 0.8 # 计算税后收入
# 行运算(广播机制)
mean_income = df['收入'].mean() # 计算平均收入
df['高于平均'] = df['收入'] > mean_income
```
#### 5. 迭代 DataFrame
**迭代列**:
```python
for column in df.columns:
col_data = df[column] # 获取列数据(Series)
print(f"列名: {column}")
print(col_data.head()) # 打印前几行数据[^3]
```
**迭代行**:
```python
# 高效方法(使用 itertuples)
for row in df.itertuples():
print(f"{row.姓名} 来自 {row.城市}")
# 方法 2(使用 iterrows)
for index, row in df.iterrows():
print(f"索引 {index}: {row['年龄']}岁")
```
#### 6. 数据分组与聚合
```python
# 按城市分组计算平均年龄
grouped = df.groupby('城市')['年龄'].mean()
# 多级聚合
agg_result = df.groupby('城市').agg({
'年龄': ['mean', 'max', 'min'],
'收入': 'sum'
})
```
#### 7. 数据合并
```python
# 垂直合并(添加行)
df2 = pd.DataFrame({'姓名': ['赵六'], '年龄': [32], '城市': ['深圳']})
combined = pd.concat([df, df2])
# 水平合并(添加列)
df_info = pd.DataFrame({'姓名': ['张三', '李四', '王五'], '部门': ['技术部', '市场部', '财务部']})
merged = pd.merge(df, df_info, on='姓名')
```
#### 8. 数据可视化
```python
import matplotlib.pyplot as plt
# 绘制柱状图
df.plot(kind='bar', x='姓名', y='收入')
plt.title('收入分布')
plt.show()
# 绘制箱线图
df.boxplot(column='年龄', by='城市')
plt.suptitle('') # 移除自动标题
plt.title('不同城市年龄分布')
plt.show()
```
#### 9. 性能优化技巧
1. **避免循环**:使用向量化操作替代 `for` 循环
2. **使用高效数据类型**:`df = df.astype({'年龄': 'int8'})`
3. **分块处理大数据**:`pd.read_csv('large.csv', chunksize=10000)`
4. **使用分类数据**:`df['城市'] = df['城市'].astype('category')`
> 关键提示:操作 DataFrame 时,优先使用 Pandas 内置函数而非 Python 原生循环,性能可提升 10-100 倍[^5]。