Python-将title()函数应用于列中的值
我已经在我的数据框架上为python编写了一些方法。然而,我想知道为什么我的函数不能正常工作,为什么它似乎不能正确应用,下面是我的代码,后面是相应的屏幕截图:Python-将title()函数应用于列中的值,python,pandas,Python,Pandas,我已经在我的数据框架上为python编写了一些方法。然而,我想知道为什么我的函数不能正常工作,为什么它似乎不能正确应用,下面是我的代码,后面是相应的屏幕截图: def clean_belfast_data(df): df.dropna(subset=['Ward Name'], inplace=True) df.reset_index(drop=True, inplace=True) #Perhaps I can't use inplace for this.
def clean_belfast_data(df):
df.dropna(subset=['Ward Name'], inplace=True)
df.reset_index(drop=True, inplace=True)
#Perhaps I can't use inplace for this.
df['Ward Name'].str.title().inplace=True
return df
改变
df['Ward Name'].str.title().inplace=True
到
行
df['Ward Name'].str.title().inplace=True
无效。我不知道为什么它运行时没有出错,但它没有按您的意思运行。您有两件事需要更改
df['Ward Name'].str.title().inplace=True
这是错误的
另外,不要忘记将其重新分配,通常我们不会使用inplace=True
直接修改原始数据
def clean_belfast_data(df1):
df=df1.copy()
df.dropna(subset=['Ward Name'], inplace=True)
df.reset_index(drop=True, inplace=True)
#Perhaps I can't use inplace for this.
df['Ward Name']=df['Ward Name'].str.title()
return df
CrimeData_1=clean_belfast_data(crimeDate)
不需要创建函数。您的操作没有存储,这是您的问题
df['Ward Name']= df['Ward Name'].dropna()
然后
df['Ward Name']= df['Ward Name'].dropna()
df['Ward Name'] = df['Ward Name'].str.title()