使用loc命令替换值

时间:2019-07-02 10:51:41

标签: python pandas

有一个数据框,我需要使用263将replace的值设置为大于512。

因此,我使用此代码行首先过滤了我的索引:

df.loc[df['Fare']>512]['Fare'].astype(int)

这是结果:

258     512
679     512
737     512
1234    512
Name: Fare, dtype: int64

这看起来不错!因为它过滤了所有4行,其值大于512。 现在,我需要将此值替换为263:

df.loc[df['Fare']>512]['Fare']=df.loc[df['Fare']>512]['Fare'].astype(int).replace({512:263},inplace=True)

但是它不会改变我的数据框中的任何内容。 例如,当我搜索索引737时,我发现了这一点:

df.iloc[737]

结果:

Age                                35
Fare                          512.329

因此,尽管有上述代码,票价仍未更改为263。

3 个答案:

答案 0 :(得分:2)

使用 fun getDataForUser(newUser: String?): LiveData<UserDataResult> { if (newUser == null) { return MutableLiveData<UserDataResult>().apply { value = null } } return userOnlineDataSource.getOnlineTime(newUser) .combineAndCompute(userCheckinsDataSource.getCheckins(newUser)) { a,b-> UserDataSuccess(a, b) } } 时,您要使用.loc而不是[row, col]

尝试:

[row][col]

答案 1 :(得分:2)

你有什么理由不只是做

condition = df['Fare'].astype(int) > 512
df.loc[condition, 'Fare'] = 263

condition是一个布尔序列,.loc只会将该序列中值为True的行分配给您所需的值。

答案 2 :(得分:2)

删除inplace = True选项。

df.loc[df['Fare']>512]['Fare']=df.loc[df['Fare']>512]['Fare'].astype(int).replace({512:263})

或者干脆不挑衅。

df.loc[df['Fare']>512]['Fare'].astype(int).replace({512:263}, inplace=True)

来自replace docs

  

inplace:bool,默认为False
  如果为True,则到位。注意:这将修改此对象的任何其他视图(例如,DataFrame中的列)。 如果为True,则返回呼叫者。

现在,您正在就地修改数据框,但是赋值运算符=返回了调用方,因此您将用原始值重写您的编辑。

编辑

实际上,在我的inplace = True版本(pandas 0.24.0)中,它不会返回任何内容,因此上述粗体字可能与版本有关(文档指的是pandas 0.24.2)。

请注意,使用.loc过滤数据然后使用replace是多余的:.replace({512:263})仅转换值512,而无需在使用{{1之前选择该值}}。
如果您这样做:

.loc

您得到相同的结果。

相关问题