python定义csv多个表头
时间: 2023-07-12 21:40:20 浏览: 52
CSV文件只支持单个表头,但是可以使用Pandas库来读取和写入包含多个层级的表头的数据。以下是一个示例代码:
```python
import pandas as pd
# 定义数据
data = {
('info', 'name'): ['Alice', 'Bob', 'Charlie'],
('info', 'age'): [25, 30, 35],
('info', 'gender'): ['F', 'M', 'M'],
('score', 'math'): [90, 80, 70],
('score', 'english'): [85, 90, 95]
}
# 定义DataFrame
df = pd.DataFrame(data)
# 显示DataFrame
print(df)
```
输出:
```
info score
name age gender math english
0 Alice 25 F 90 85
1 Bob 30 M 80 90
2 Charlie 35 M 70 95
```
在这个示例中,我们首先定义了一个字典`data`,其中包含了两个层级的表头和相应的数据。然后,我们使用`pd.DataFrame()`函数将这个字典转换为DataFrame。在这个过程中,我们使用了元组来表示表头的多个层级。最后,我们使用`print()`函数显示DataFrame。在这个DataFrame中,`info`和`score`是第一层级的表头,而`name`、`age`、`gender`、`math`和`english`是第二层级的表头。可以使用`.columns`属性查看DataFrame的表头结构。