利用python代码读取csv或者csv.gz为dataframe
时间: 2023-06-21 14:21:33 浏览: 200
要将 CSV 或 CSV 压缩文件读取为 DataFrame,可以使用 pandas 库。pandas 提供了 `read_csv()` 函数,该函数可以读取 CSV 或 CSV 压缩文件,并将其转换为 DataFrame。下面是读取 CSV 和 CSV 压缩文件为 DataFrame 的示例代码:
1. 读取 CSV 文件为 DataFrame
```python
import pandas as pd
df = pd.read_csv('example.csv')
print(df)
```
在上面的示例中,我们使用 `read_csv()` 函数读取名为 `example.csv` 的 CSV 文件,并将其转换为 DataFrame。然后,我们使用 `print()` 函数打印 DataFrame。
2. 读取 CSV 压缩文件为 DataFrame
```python
import pandas as pd
import gzip
with gzip.open('example.csv.gz', 'rt') as csv_file:
df = pd.read_csv(csv_file)
print(df)
```
在上面的示例中,我们使用 `gzip.open` 函数读取名为 `example.csv.gz` 的压缩的 CSV 文件,并将其转换为 DataFrame。然后,我们使用 `print()` 函数打印 DataFrame。
需要注意的是,当使用 `gzip.open` 打开文件时,需要将文件模式设置为 `'rt'`,以便能够读取文本文件。
阅读全文
相关推荐

















