一望码田深似海 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 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?