python - Python:如何修复 Python 中的 AttributeError?
问题描述
我有代码:
df_mean_woman = df_mean_woman.rename(index = {"Less than 1 year":0}, inplace = True)
df_mean_woman
当我运行它时,我得到了错误
AttributeError Traceback (most recent call last)
<ipython-input-136-94a5cc6acf63> in <module>
----> 1 df_woman = df_woman.rename(index = {"Less than 1 year":0},
2 #"More than 50 years":int(51)},
3 inplace = True)
4 df_woman
AttributeError: 'NoneType' object has no attribute 'rename'
虽然当我简单地输入时错误就消失了,df_mean_woman.rename(index = {"Less than 1 year":0}, inplace = True)
但我不能简单地这样做,因为我需要稍后再次调用 df。我已经尝试做很多事情来解决这个问题,但似乎没有任何效果。我不认为这是因为“不到 1 年”拼写不正确。我的主要问题似乎是当我打印出 df_mean_woman (重命名之前)时,据说 df 不存在。当我重新运行 Juptyr 时,我可以打印出 df,但打印出来的都是“无”。
我的完整代码是
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
df = pd.read_csv('data.csv')
%matplotlib inline
df_new = df.copy()
df_new = df_new.drop(['Age1stCode','CompTotal','Respondent', 'MainBranch', 'Hobbyist', 'Age', 'CompFreq', 'Country', 'CurrencyDesc', 'CurrencySymbol', 'DatabaseDesireNextYear', 'DatabaseWorkedWith', 'DevType', 'EdLevel', 'Employment', 'Ethnicity', 'JobFactors', 'JobSat', 'JobSeek', 'LanguageDesireNextYear', 'LanguageWorkedWith', 'MiscTechDesireNextYear', 'MiscTechWorkedWith', 'NEWCollabToolsDesireNextYear', 'NEWCollabToolsWorkedWith', 'NEWDevOps', 'NEWDevOpsImpt', 'NEWEdImpt', 'NEWJobHunt', 'NEWJobHuntResearch', 'NEWLearn', 'NEWOffTopic', 'NEWOnboardGood', 'NEWOtherComms', 'NEWOvertime', 'NEWPurchaseResearch', 'NEWPurpleLink', 'NEWSOSites', 'NEWStuck', 'OpSys', 'OrgSize', 'PlatformDesireNextYear', 'PlatformWorkedWith', 'PurchaseWhat', 'Sexuality', 'SOAccount', 'SOComm', 'SOPartFreq', 'SOVisitFreq', 'SurveyEase', 'SurveyLength', 'Trans', 'UndergradMajor', 'WebframeDesireNextYear', 'WebframeWorkedWith', 'WelcomeChange', 'WorkWeekHrs', 'YearsCodePro'], axis = 'columns')
df_new = df_new.dropna()
df_new
df_woman = df_new.drop(index=df_new[df_new['Gender'] != 'Woman'].index, inplace=True)
df_woman = df_new
df_woman = df_woman.drop(['Gender'], axis ='columns')
df_news = df_new.copy()
df_woman = df_woman.rename(index = {"Less than 1 year":int(0)},
#"More than 50 years":int(51)},
inplace = True)
df_woman['YearsCode'] = df_woman['YearsCode'].apply(lambda x: '{0:0>2}'.format(x))
df_mean_woman = df_woman.groupby('YearsCode')['ConvertedComp'].mean().sort_index()
df_mean_woman
解决方案
df_woman = df_new.drop(index=df_new[df_new['Gender'] != 'Woman'].index, inplace=True)
.drop()
None
时返回inplace=True
。
见这里https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.drop.html
推荐阅读
- oracle-sqldeveloper - 如何防止连接在 SQL Developer 中被重置/强制关闭?
- java - Netty HTTP/2 客户端在连接到 https://http2.golang.org/ 时失败
- html - 在 HTML 中制作两行表头
- c++ - 括号内的标题是否必须始终高于 C++ 的引用标题?
- nuget - NuGet 包在错误的文件夹中寻找依赖项
- html - 将 routerLInk 放在标签上,但标签不可点击 angular 6
- c++ - 根据变量在 Qt UI 中选中/取消选中复选框
- javascript - Bootstrap Modal中的JQuery验证表单在验证后不会提交
- python - 你如何逃避这个while循环?
- android - android:显示来自 ArrayAdapter 的单个视图