相关疑难解决方法(0)

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


我已经创建了一个pandas DataFrame

df = DataFrame(index=['A','B','C'], columns=['x','y'])
Run Code Online (Sandbox Code Playgroud)

得到了这个

    x    y
A  NaN  NaN
B  NaN  NaN
C  NaN  NaN


然后我想为特定单元格赋值,例如行'C'和列'x'.我期望得到这样的结果:

    x    y
A  NaN  NaN
B  NaN  NaN
C  10  NaN

使用此代码:

df.xs('C')['x'] = 10
Run Code Online (Sandbox Code Playgroud)

但是df的内容没有改变.在数据帧中它只是Nan的.

有什么建议?

python dataframe pandas

396
推荐指数
17
解决办法
69万
查看次数

如何将StackOverflow中的DataFrame复制/粘贴到Python中

问题答案中,用户经常发布DataFrame他们的问题/答案适用的示例:

In []: x
Out[]: 
   bar  foo
0    4    1
1    5    2
2    6    3
Run Code Online (Sandbox Code Playgroud)

能够将它DataFrame放入我的Python解释器中是非常有用的,这样我就可以开始调试问题,或者测试答案.

我怎样才能做到这一点?

python clipboard pandas

39
推荐指数
2
解决办法
6203
查看次数

Pandas:索引更新和更改按位置访问的值

我在Python Pandas数据帧上有两个与索引相关的问题.

import pandas as pd
import numpy as np
df = pd.DataFrame({'id' : range(1,9),
                'B' : ['one', 'one', 'two', 'three',
                       'two', 'three', 'one', 'two'],
                'amount' : np.random.randn(8)})

df = df.ix[df.B != 'three'] # remove where B = three
df.index
>>  Int64Index([0, 1, 2, 4, 6, 7], dtype=int64) # the original index is preserved.
Run Code Online (Sandbox Code Playgroud)

1)我不明白为什么修改数据帧后索引不会自动更新.有没有办法在修改数据帧时自动更新索引?如果没有,那么最有效的手动方式是什么?

2)我希望能够B将第5个元素的列设置df为"3".但df.iloc[5]['B'] = 'three'不这样做.我查看了手册,但没有介绍如何更改按位置访问的特定单元格值.

如果我按行名访问,我可以这样做:df.loc[5,'B'] = 'three'但我不知道索引访问等价物是什么.

PS Link1link2是我第二个问题的相关答案.但是,他们没有回答我的问题.

python indexing dataframe pandas

5
推荐指数
2
解决办法
2万
查看次数

标签 统计

pandas ×3

python ×3

dataframe ×2

clipboard ×1

indexing ×1