一望码田深似海 2021-11-10 11:12 采纳率: 100%
浏览 625
已结题

python中出现错误 ValueError: Series.replace cannot use dict-value and non-None to_replace 如何解决?


#导入工具包并加载数据
#-*- coding: utf-8 -*-
import pandas as pd
import numpy as np
# 可视化
import matplotlib.pyplot as plt 
import seaborn as sns 
# 机器学习---用于用户流失预测
from sklearn.model_selection import train_test_split, GridSearchCV
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.pipeline import Pipeline
from sklearn.metrics import accuracy_score
#plt.rcParams['font.family'] = 'SimHei'
#plt.rcParams['axes.unicode_minus'] = False
#读取数据
dx = pd.read_csv('telecom.csv')
# 查看数据集大小
print(dx.shape)
# 运行结果:(7043, 21)

# 设置查看不省略
##列名与数据对其显示
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)
##显示所有列
pd.set_option('display.max_columns', None)
##显示所有行
pd.set_option('display.max_rows', None)

# 查看前5条数据
print(dx.head())
# 查看数据是否存在Null
print(pd.isnull(dx).sum()) # Null计数
# 查看数据类型
print(dx.info())
#dx.dtypes
#dx[['TotalCharges']].astype(float)
#ValueError: could not convert string to float:
#强制转换为数字,不可转换的变为NaN
dx['TotalCharges']=dx['TotalCharges'].apply(pd.to_numeric, errors='coerce')
test=dx.loc[:,'TotalCharges'].value_counts().sort_index()
print(test.sum()) #运行结果:7032
# 查看缺失数据
print(dx.tenure[dx['TotalCharges'].isnull().values==True])
# 统计缺失总数
print((dx.tenure[dx['TotalCharges'].isnull().values==True]).value_counts())
#运行结果:0   11
print(dx.isnull().any())
print(dx[dx['TotalCharges'].isnull().values==True] [['tenure','MonthlyCharges','TotalCharges']])
#将总消费额填充为月消费额
dx.loc[:,'TotalCharges'].replace(to_replace=np.nan,value=dx.loc[:,'MonthlyCharges'],inplace=True)
#查看是否替换成功
print(dx[dx['tenure']==0][['tenure','MonthlyCharges','TotalCharges']])

到这就提示错误ValueError: Series.replace cannot use dict-value and non-None to_replace

img


求解

[](链接:


提取码:ad39)

  • 写回答

1条回答 默认 最新

  • 於黾 2021-11-10 11:22
    关注

    报错很清楚了,告诉你不能把空替换成数据
    你可以把任何匹配到的字符替换成空,但是不能倒过来
    没法把空替换成数据

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 11月18日
  • 已采纳回答 11月10日
  • 创建了问题 11月10日

悬赏问题

  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题
  • ¥30 酬劳2w元求合作写文章
  • ¥15 在现有系统基础上增加功能