我知道这两个类似的问题:
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/