python数据清洗案例
时间: 2023-07-25 21:42:20 浏览: 47
一个常见的 Python 数据清洗案例是处理缺失数据。假设有一个包含学生考试成绩的数据集,其中有一些学生的成绩缺失。我们可以使用 Pandas 库来处理这些缺失值。
首先,我们需要导入 Pandas 库和包含数据的 CSV 文件:
```python
import pandas as pd
df = pd.read_csv('exam_scores.csv')
```
然后,我们可以使用 Pandas 的 `DataFrame.fillna()` 方法来填充缺失值。例如,我们可以将缺失值填充为每个学科的平均值:
```python
df['math_score'].fillna(df['math_score'].mean(), inplace=True)
df['english_score'].fillna(df['english_score'].mean(), inplace=True)
df['science_score'].fillna(df['science_score'].mean(), inplace=True)
```
最后,我们可以将处理后的数据保存为新的 CSV 文件:
```python
df.to_csv('exam_scores_cleaned.csv', index=False)
```
这样就完成了缺失数据的清洗处理。
相关问题
python数据清洗案例 把时间改为标准时间格式
一个常见的 Python 数据清洗案例是将时间数据转换为标准时间格式。假设有一个包含交易记录的数据集,其中包含交易时间的字符串数据。我们可以使用 Python 内置的 `datetime` 模块来将这些字符串转换为标准时间格式。
首先,我们需要导入 `datetime` 模块和包含数据的 CSV 文件:
```python
import csv
from datetime import datetime
with open('transactions.csv', 'r') as f:
reader = csv.reader(f)
next(reader) # skip header row
for row in reader:
transaction_time = row[3] # assuming transaction time is in column 3
# convert string to datetime object
dt = datetime.strptime(transaction_time, '%Y-%m-%d %H:%M:%S')
# convert datetime object to ISO format
iso_time = dt.isoformat()
# update row with new ISO format time
row[3] = iso_time
```
在上面的代码中,我们首先使用 `csv.reader` 对象读取 CSV 文件中的数据,并跳过第一行头信息。然后,我们迭代每一行数据,将交易时间的字符串转换为 `datetime` 对象,并将其转换为 ISO 格式的字符串。最后,我们更新每行数据中的交易时间,以便它包含新的 ISO 格式时间。
最后,我们可以将处理后的数据保存为新的 CSV 文件:
```python
with open('transactions_cleaned.csv', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerow(['col1', 'col2', 'col3', 'transaction_time']) # write header row
writer.writerows(rows)
```
这样就完成了将时间数据转换为标准时间格式的清洗处理。
python爬虫数据清洗案例
当然,我可以为您提供一个简单的 Python 爬虫数据清洗案例。假设我们要爬取一个网页上的新闻标题,并对标题进行清洗和整理。
首先,我们需要安装必要的库。在 Python 中,我们可以使用 `requests` 库来发送 HTTP 请求,使用 `beautifulsoup4` 库来解析 HTML。
```python
pip install requests beautifulsoup4
```
接下来,我们可以编写爬虫代码。下面是一个示例:
```python
import requests
from bs4 import BeautifulSoup
# 发送 HTTP 请求并获取网页内容
url = 'https://example.com/news'
response = requests.get(url)
html = response.text
# 使用 BeautifulSoup 解析 HTML
soup = BeautifulSoup(html, 'html.parser')
# 查找新闻标题的标签和属性
title_tags = soup.find_all('h2', class_='news-title')
# 清洗和整理新闻标题
cleaned_titles = []
for tag in title_tags:
title = tag.text.strip() # 去除标题前后的空白字符
cleaned_titles.append(title)
# 打印清洗后的新闻标题
for title in cleaned_titles:
print(title)
```
在上面的示例中,我们首先发送 HTTP 请求并获取网页内容,然后使用 BeautifulSoup 解析 HTML。接着,我们查找新闻标题的标签和属性,并对标题进行清洗和整理。最后,我们打印清洗后的新闻标题。
请注意,这只是一个简单的示例,实际的数据清洗可能涉及更复杂的操作,例如正则表达式匹配、文本处理等。具体的清洗方法取决于您所爬取的网页和数据的结构。