如何使用填充方法


example = {
'Team':['Australia', 'England', 'South Africa', 'Australia', 'England', 'India', 
'India', 'South Africa', 'England', 'India','India','Australia'],
'Player':['Ricky Ponting', 'Joe Root', 'Hashim Amla', 'David Warner', 
'Jos Buttler', 'Virat Kohli', 'Rohit Sharma', 'David Miller', 
'Eoin Morgan', 'Dinesh Karthik',np.nan ,np.nan],                  
'Runs':[345, 336, 689, 490, 989, 672, 560, 455, 342, 376,370,400],
'Salary':[34500, 33600, 68900, 49000, 98899, 67562, 56760, 45675, 34542, 31176,
35000, 34000] 
}
df = pd.DataFrame(example)

现在我想将'nan'值替换为'Joe Root',其中Team == 'India'我已经尝试了以下方法,没有错误:

df.loc[df.Team == 'India'].fillna(value = 'Joe Root')

但是当我使用下面的方法时,它给出了一个错误:

df.loc[df.Team == 'India'].fillna('Joe Root',inplace = True)
有谁能帮帮我吗?

您的代码df.loc[df.Team == 'India'].fillna('Joe Root',inplace = True)正在切片数据帧,然后试图在原地使用。即创建临时数据帧并更新它(inplace = True)。如果像下面这样使用

,它可以返回部分更新的数据帧
my_temp=df.loc[df.Team == 'India']
my_temp.fillna('Joe Root',inplace = True)
my_temp

这里的目的是更新df,所以你可以试试

df.loc[df.Team == 'India','Player']=df.loc[df.Team == 'India','Player'].fillna(value='Joe Root')

像这样改变选区:

df[df.Team == 'India'] = df[df.Team == 'India'].fillna(value = 'Joe Root')
# selection = selection.fillna(value)

最新更新