如何在 pandas 中设置特定的单元格值? [英] How set a particular cell value in pandas?

查看:78
本文介绍了如何在 pandas 中设置特定的单元格值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在熊猫数据框中设置一个值.

I am trying to set a value in panda dataframe.

ZEROS = np.zeros((4,4), dtype=np.int)

df = pd.DataFrame(ZEROS,  columns=['A1','B1','C1','D1'])
df.at[2,3] = 32
df

我不希望整列输入NaN,预期输出如下:

I don't want NaN for the entire column, the expected output is below:

使用numpy,我可以像下面这样设置值

Using numpy I am able to set the value like below

ZEROS[1][3] = 44

输出:

array([[ 0,  0,  0,  0],
       [ 0,  0,  0, 44],
       [ 0,  0,  0,  0],
       [ 0,  0,  0,  0]])

推荐答案

使用 pd.DataFrame.iat 来引用和/或分配给单个单元格的顺序位置.

Use pd.DataFrame.iat to reference and/or assign to the ordinal location of a single cell.

ZEROS = np.zeros((4,4), dtype=np.int)

df = pd.DataFrame(ZEROS,  columns=['A1','B1','C1','D1'])
df.iat[2,3] = 32
df

   A1  B1  C1  D1
0   0   0   0   0
1   0   0   0   0
2   0   0   0  32
3   0   0   0   0


您也可以使用iloc,但是,iloc可以采用类似输入的数组.这使iloc更加灵活,但也需要更多开销.因此,如果您只想更改单个单元格,请使用iat


You could also use iloc however, iloc can also take array like input. This makes iloc more flexible but also requires more overhead. Therefore, if it is only a single cell you want to change... use iat

另请参阅此帖子

loc/iloc/at/iat/set_value

这篇关于如何在 pandas 中设置特定的单元格值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆