python读取csv格式数据
时间: 2023-12-05 08:40:32 浏览: 87
以下是Python读取CSV格式数据的5种方式:
1. 使用csv模块的reader方法逐行读取CSV文件并将其转换为列表格式:
```python
import csv
with open('file.csv', newline='') as csvfile:
reader = csv.reader(csvfile, delimiter=',', quotechar='"')
for row in reader:
print(', '.join(row))
```
2. 使用csv模块的DictReader方法逐行读取CSV文件并将其转换为字典格式:
```python
import csv
with open('file.csv', newline='') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row)
```
3. 使用pandas库的read_csv方法读取CSV文件并将其转换为DataFrame格式:
```python
import pandas as pd
df = pd.read_csv('file.csv')
print(df)
```
4. 使用numpy库的loadtxt方法读取CSV文件并将其转换为数组格式:
```python
import numpy as np
data = np.loadtxt('file.csv', delimiter=',', skiprows=1)
print(data)
```
5. 使用Python内置的csv模块和zip函数将CSV文件中的每一行转换为一个字典:
```python
import csv
with open('file.csv', newline='') as csvfile:
reader = csv.reader(csvfile)
headers = next(reader)
data = [dict(zip(headers, row)) for row in reader]
print(data)
```
阅读全文