python中要对csv文件中出现的np.inf和np.NAN如何删除,代码如何
时间: 2024-02-15 21:02:29 浏览: 312
你可以使用 pandas 库来读取 csv 文件,并通过 replace 和 dropna 方法删除 np.inf 和 np.nan。以下是代码示例:
```python
import pandas as pd
import numpy as np
# 读取 csv 文件
df = pd.read_csv('filename.csv')
# 将 np.inf 替换为 NaN
df.replace([np.inf, -np.inf], np.nan, inplace=True)
# 删除包含 NaN 的行
df.dropna(inplace=True)
# 保存结果
df.to_csv('new_filename.csv', index=False)
```
这段代码会将原始 csv 文件中的 np.inf 替换为 NaN,然后删除包含 NaN 的行,并将结果保存为一个新的 csv 文件。请将 `filename.csv` 替换为你自己的文件名,注意文件路径的正确性。
相关问题
解决import pandas as pd import numpy as np # 读取数据 train = pd.read_csv("D:\数据挖掘\实验\实验六\clean_train.csv") test = pd.read_csv("D:\数据挖掘\实验\实验六\clean_test.csv") # 抽取正负样本 train = train[train['label'] == 1].sample(sum(train['label'] == 1)).append(train[train['label'] == 0].sample(sum(train['label'] == 0))) test = test[test['label'] == 1].sample(sum(test['label'] == 1)).append(test[test['label'] == 0].sample(sum(test['label'] == 0))) # 删除列 x_train = train.drop(['user_id', 'merchant_id', 'coupon_id','date_received', 'date'], axis=1) x_test = test.drop(['user_id', 'merchant_id', 'coupon_id','date_received', 'date', 'label'], axis=1) # 处理无穷数据(无穷数据大或者无穷数据小) x_train[np.isinf(x_train)] = 0 x_test[np.isinf(x_test)] = 0from sklearn.tree import DecisionTreeClassifier model_dt1 = DecisionTreeClassifier(max_leaf_nodes=16, random_state=123).fit(x_train.drop(['label'], axis=1), x_train['label'])报错ValueError: Input contains NaN, infinity or a value too large for dtype('float32').问题
你在处理无穷数据时使用了 np.isinf() 函数,但是你并没有处理 NaN 值。你可以使用 Pandas 库中的 fillna() 函数来处理 NaN 值。下面是一个处理 NaN 和无穷数据的代码示例:
```python
import pandas as pd
import numpy as np
from sklearn.tree import DecisionTreeClassifier
# 读取数据
train = pd.read_csv("D:\数据挖掘\实验\实验六\clean_train.csv")
test = pd.read_csv("D:\数据挖掘\实验\实验六\clean_test.csv")
# 抽取正负样本
train = train[train['label'] == 1].sample(sum(train['label'] == 1)).append(train[train['label'] == 0].sample(sum(train['label'] == 0)))
test = test[test['label'] == 1].sample(sum(test['label'] == 1)).append(test[test['label'] == 0].sample(sum(test['label'] == 0)))
# 删除列
x_train = train.drop(['user_id', 'merchant_id', 'coupon_id','date_received', 'date'], axis=1)
x_test = test.drop(['user_id', 'merchant_id', 'coupon_id','date_received', 'date', 'label'], axis=1)
# 处理无穷数据和 NaN
x_train = x_train.replace([np.inf, -np.inf], np.nan)
x_train.fillna(0, inplace=True)
x_test = x_test.replace([np.inf, -np.inf], np.nan)
x_test.fillna(0, inplace=True)
# 训练决策树模型
model_dt1 = DecisionTreeClassifier(max_leaf_nodes=16, random_state=123).fit(x_train.drop(['label'], axis=1), x_train['label'])
```
这样处理之后,你的数据集中就不应该包含 NaN 和无穷值了。
用python完成(1)爬取指定网址的金属铜的库存数据(包括库存和库存变动),保存在本地(csv文件) 网址:https://data.eastmoney.com/ifdata/kcsj.html (2)提供每日更新功能,用每日更新的数据,更新本地库存数据。 (3)计算最近一周和最近一月库存变动比例,存入上述数据文件中。
A:
1)爬取金属铜的库存数据,并保存在本地csv文件中:
``` python
import requests
import csv
from bs4 import BeautifulSoup
#设置访问网址
url = "https://data.eastmoney.com/ifdata/kcsj.html"
#使用requests模块发送GET请求
response = requests.get(url)
#使用BeautifulSoup解析HTML页面
soup = BeautifulSoup(response.text, "html.parser")
#获取表格中的数据
table_data = soup.find_all("tr")
#创建csv文件,并写入数据
with open("copper_inventory.csv", "w", encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
#遍历表格数据,写入csv文件
for row in table_data:
#获取表格每一行的数据
td_list = row.find_all("td")
td_data = []
#将数据填充到列表中
for td in td_list:
td_data.append(td.text.strip())
#写入到csv文件中
writer.writerow(td_data)
```
2)实现每日更新功能,使用同样的方法获取新的数据并追加到本地csv文件中:
``` python
import requests
import csv
from bs4 import BeautifulSoup
#设置访问网址
url = "https://data.eastmoney.com/ifdata/kcsj.html"
#使用requests模块发送GET请求
response = requests.get(url)
#使用BeautifulSoup解析HTML页面
soup = BeautifulSoup(response.text, "html.parser")
#获取表格中的数据
table_data = soup.find_all("tr")
#打开csv文件,将新数据追加到文件中
with open("copper_inventory.csv", "a", encoding='utf-8', newline='') as csvfile:
writer = csv.writer(csvfile)
#遍历表格数据,写入csv文件
for row in table_data:
#获取表格每一行的数据
td_list = row.find_all("td")
td_data = []
#将数据填充到列表中
for td in td_list:
td_data.append(td.text.strip())
#写入到csv文件中
writer.writerow(td_data)
```
3)计算最近一周和最近一月库存变动比例,存入上述数据文件中:
可以通过使用pandas模块来进行数据处理和计算。首先使用pandas读取本地csv文件,并将最近一周和一月的数据筛选出来。接着,使用pandas自带的计算函数计算变动比例,最后将结果保存写入到csv文件中:
``` python
import pandas as pd
import numpy as np
#读取本地csv文件
df = pd.read_csv("copper_inventory.csv", encoding='utf-8')
#筛选最近一周的数据
recent_week = df[df['日期'] > pd.Timestamp.today() - pd.Timedelta(days=7)]
#筛选最近一月的数据
recent_month=df[df['日期'] > pd.Timestamp.today() - pd.Timedelta(days=30)]
#计算最近一周和最近一月的数据变动比例
recent_week['库存变动比例'] = recent_week['库存'].astype(float).pct_change().replace([np.inf,-np.inf,np.nan],0)
recent_month['库存变动比例'] = recent_month['库存'].astype(float).pct_change().replace([np.inf,-np.inf,np.nan],0)
#将结果写入到csv文件
recent_week.to_csv('copper_inventory.csv',mode ='w', encoding='utf-8',header=True, index=False)
recent_month.to_csv('copper_inventory.csv', mode='a', encoding='utf-8',header=False, index=False)
```
阅读全文
相关推荐
















