DataFrame怎么导入
时间: 2024-10-10 18:15:41 浏览: 40
在Python中,特别是使用pandas库处理数据时,DataFrame通常是从CSV、Excel、SQL数据库、JSON文件或网页等数据源导入的。以下是几种常见的导入方式:
1. **从CSV文件**:
```python
import pandas as pd
df = pd.read_csv('filename.csv')
```
2. **从Excel文件**:
```python
df = pd.read_excel('filename.xlsx')
```
3. **从SQL查询** (通过SQLAlchemy或sqlite3):
```python
import sqlite3
conn = sqlite3.connect('database.db')
query = "SELECT * FROM table_name"
df = pd.read_sql_query(query, conn)
```
4. **从JSON文件**:
```python
df = pd.read_json('filename.json', orient='records')
```
5. **从网站(API)获取** (例如使用requests库):
```python
import requests
url = 'https://api.example.com/data'
data = requests.get(url).json()
df = pd.DataFrame(data)
```
6. **直接从Pandas读取数据(例如,内存中存储的数据)**:
```python
data_dict = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data_dict)
```
每种导入方法的具体语法可能会有所不同,取决于数据的来源和格式。
阅读全文
相关推荐


















