本文翻译自:Set value for particular cell in pandas DataFrame using index
I've created a Pandas DataFrame 我创建了一个Pandas DataFrame
df = DataFrame(index=['A','B','C'], columns=['x','y'])
and got this 并得到了
x y A NaN NaN B NaN NaN C NaN NaN
Then I want to assign value to particular cell, for example for row 'C' and column 'x'. 然后,我想为特定的单元格赋值,例如行“ C”和列“ x”。 I've expected to get such result: 我期望得到这样的结果:
x y A NaN NaN B NaN NaN C 10 NaN
with this code: 使用此代码:
df.xs('C')['x'] = 10
but contents of df
haven't changed. 但是df
内容没有改变。 It's again only NaN
s in DataFrame. 再次仅是DataFrame中的NaN
。
Any suggestions? 有什么建议么?
参考:https://stackoom.com/question/w4xU/使用索引为pandas-DataFrame中的特定单元格设置值
RukTech's answer , df.set_value('C', 'x', 10)
, is far and away faster than the options I've suggested below. RukTech的答案 df.set_value('C', 'x', 10)
比我在下面建议的选项要快得多。 However, it has been slated for deprecation . 但是,已将其淘汰 。
Going forward, the recommended method is .iat/.at
. 展望未来, 推荐的方法是.iat/.at
。
Why df.xs('C')['x']=10
does not work: 为什么df.xs('C')['x']=10
不起作用:
df.xs('C')
by default, returns a new dataframe with a copy of the data, so df.xs('C')
默认情况下,返回带有数据副本的新数据df.xs('C')
,因此
df.xs('C')['x']=10
modifies this new dataframe only. 仅修改此新数据框。
df['x']
returns a view of the df
dataframe, so df['x']
返回df
数据帧的视图,因此
df['x']['C'] = 10
modifies df
itself. 修改df
本身。
Warning : It is sometimes difficult to predict if an operation returns a copy or a view. 警告 :有时很难预测操作是否返回副本或视图。 For this reason the docs recommend avoiding assignments with "chained indexing" . 因此, 文档建议避免使用“链接索引”进行赋值 。
So the recommended alternative is 所以推荐的替代方法是
df.at['C', 'x'] = 10
which does modify df
. 确实会修改df
。
In [18]: %timeit df.set_value('C', 'x', 10)
100000 loops, best of 3: 2.9 µs per loop
In [20]: %timeit df['x']['C'] = 10
100000 loops, best of 3: 6.31 µs per loop
In [81]: %timeit df.at['C', 'x'] = 10
100000 loops, best of 3: 9.2 µs per loop
The recommended way (according to the maintainers) to set a value is: 推荐的方法(根据维护者)是:
df.ix['x','C']=10
Using 'chained indexing' ( df['x']['C']
) may lead to problems. 使用“链式索引”( df['x']['C']
)可能会导致问题。
See: 看到:
Update: The .set_value
method is going to be deprecated . 更新: .set_value
方法将不推荐使用 。 .iat/.at
are good replacements, unfortunately pandas provides little documentation .iat/.at
是很好的替代品,不幸的是熊猫提供的文件很少
The fastest way to do this is using set_value . 最快的方法是使用set_value 。 This method is ~100 times faster than .ix
method. 此方法比.ix
方法快100倍。 For example: 例如:
df.set_value('C', 'x', 10)
尝试使用df.loc[row_index,col_indexer] = value
This is the only thing that worked for me! 这是唯一对我有用的东西!
df.loc['C', 'x'] = 10
Learn more about .loc
here . 在此处了解有关.loc
更多信息。