pandas 如何在熊猫中设置特定的单元格值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46995270/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:42:40  来源:igfitidea点击:

How set a particular cell value in pandas?

pythonpandasnumpy

提问by ajayramesh

I am trying to set a value in panda dataframe.

我正在尝试在Pandas数据框中设置一个值。

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

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

enter image description here

在此处输入图片说明

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

我不想要NaN整列,预期的输出如下:

Using numpy I am able to set the value like below

使用 numpy 我可以设置如下值

ZEROS[1][3] = 44

output:

输出:

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

回答by piRSquared

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

使用pd.DataFrame.iat于参考和/或分配给一个小区的序号位置。

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


You could also use ilochowever, iloccan alsotake array like input. This makes ilocmore flexible but also requires more overhead. Therefore, if it is only a single cell you want to change... use iat

你也可以使用iloc但是,iloc采取类似阵列输入。这使得iloc更灵活,但也需要更多的开销。因此,如果您只想更改单个单元格...使用iat



Also see this post for more information

另请参阅此帖子以获取更多信息

loc/iloc/at/iat/set_value

loc/ iloc/ at/ iat/set_value

回答by Psidom

Use iloc:

使用iloc

df.iloc[2,3] = 32

print(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

Or if you want to modify by index and column name, use loc:

或者,如果要按索引和列名进行修改,请使用loc

df.loc[2, 'D1'] = 32