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

标签 python pandas dataframe cell nan

我创建了一个 Pandas 数据框

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

得到了这个

    x    y
A  NaN  NaN
B  NaN  NaN
C  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    y
A  NaN  NaN
B  NaN  NaN
C  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/

相关文章:

python - DataConversionWarning 在 Scikit 中拟合 RandomForestRegressor

python - 将工作表添加到从另一个工作簿创建的工作簿

python - csv.writer 在单独的列/单元格中写入单词的每个字符

Python:Pandas:将文本文件中的数据帧索引保存为列

python - 格式化 Pandas 数据框中的时间戳

python - 如何使用Series来过滤DataFrame

python - 哪个是适用于 Windows 的 Python 的最佳 IDE

python - 保存到 Pandas 数据框中的文本

c++ - 将 DataFrame 转换为 Matrix 的最有效方法,反之亦然

python - 如何使用 pandas/python 从日期和字符串的列组合中删除时间戳?