gpt4 book ai didi

python - 使用索引为 pandas DataFrame 中的特定单元格设置值

转载 作者:IT老高 更新时间:2023-10-28 12:05:21 30 4
gpt4 key购买 nike

我创建了一个 Pandas 数据框

df = DataFrame(index=['A','B','C'], columns=['x','y'])

得到了这个

    x    yA  NaN  NaNB  NaN  NaNC  NaN  NaN

Now, I would like to assign a value to particular cell, for example to row C and column x.I would expect to get this result:

    x    yA  NaN  NaNB  NaN  NaNC  10  NaN

with this code:

df.xs('C')['x'] = 10

但是,df 的内容并没有改变。数据框再次仅包含 NaNs。

有什么建议吗?

最佳答案

RukTech's answer , df.set_value('C', 'x', 10),远远快于我在下面建议的选项。但是,它一直是 slated for deprecation .

展望 future ,recommended method is .iat/.at .


为什么 df.xs('C')['x']=10 不起作用:

df.xs('C') 默认返回一个新的dataframe with a copy数据,所以

df.xs('C')['x']=10

只修改这个新的数据框。

df['x'] 返回 df 数据框的 View ,所以

df['x']['C'] = 10

修改 df 本身。

警告:有时很难预测操作是否返回副本或 View 。出于这个原因,docs recommend avoiding assignments with "chained indexing" .


所以推荐的替代方案是

df.at['C', 'x'] = 10

修改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

关于python - 使用索引为 pandas DataFrame 中的特定单元格设置值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13842088/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com