5

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

enter image description here

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

Using numpy I am able to set the value like below

ZEROS[1][3] = 44

output:

array([[ 0,  0,  0,  0],
       [ 0,  0,  0, 44],
       [ 0,  0,  0,  0],
       [ 0,  0,  0,  0]])
ajayramesh
  • 3,576
  • 8
  • 50
  • 75

2 Answers2

16

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

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


Also see this post for more information

loc/iloc/at/iat/set_value

piRSquared
  • 285,575
  • 57
  • 475
  • 624
11

Use 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:

df.loc[2, 'D1'] = 32
Psidom
  • 209,562
  • 33
  • 339
  • 356