python - Pandas 替换特定列上的值

标签 python pandas

我知道这两个类似的问题:

Pandas replace values

Pandas: Replacing column values in dataframe

我使用了一种不同的方法来替换我认为应该是最干净的值。但它不起作用。我知道如何解决它,但我想了解为什么它不起作用:

In [108]: df=pd.DataFrame([[1, 2, 8],[3, 4, 8], [5, 1, 8]], columns=['A', 'B', 'C']) 

In [109]: df
Out[109]: 
   A  B  C
0  1  2  8
1  3  4  8
2  5  1  8

In [110]: df.loc[:, ['A', 'B']].replace([1, 3, 2], [3, 6, 7], inplace=True)

In [111]: df
Out[111]: 
   A  B  C
0  1  2  8
1  3  4  8
2  5  1  8

In [112]: df.loc[:, 'A'].replace([1, 3, 2], [3, 6, 7], inplace=True)

In [113]: df
Out[113]: 
   A  B  C
0  3  2  8
1  6  4  8
2  5  1  8

如果我只对 In [112] 中的一列进行切片,则其工作方式与对 In [110] 中的多列进行切片不同。据我了解 .loc 方法,它返回一个 View 而不是一个副本。在我的逻辑中,这意味着对切片进行就地更改应该会更改整个 DataFrame。这就是 In [110] 行发生的情况。

最佳答案

以下是其中一位开发人员的回答:https://github.com/pydata/pandas/issues/11984

This should ideally show a SettingWithCopyWarning, but I think this is quite difficult to detect.

You should NEVER do this type of chained inplace setting. It is simply bad practice.

idiomatic is:

In [7]: df[['A','B']] = df[['A','B']].replace([1, 3, 2], [3, 6, 7])

In [8]: df
Out[8]: 
   A  B  C
0  3  7  8
1  6  4  8
2  5  3  8

(you can do with df.loc[:,['A','B']] as well, but more clear as above.

关于python - Pandas 替换特定列上的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34653215/

相关文章:

python - 如何使用日期时间索引和位置选择两组年份?

python - 如何将 unicode 数字转换为整数?

python - 如何动态地将多个数据帧附加在一起?

python - 用字符替换空格

python - 使用 pandasql 时在 VS Code 中使用多个制表符间距设置和注释

python - 如何从 Pandas 的嵌套字典中获取特定的键值?

路由器后面的 Python 客户端/服务器

python - 根据类型过滤类的属性

c++ - 禁用设置 python 扩展对象的属性

python - Scikit 在使用 fit() 函数时学习 GaussianProcessClassifier 内存错误