Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How set a particular cell value in 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

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]])
like image 606
ajayramesh Avatar asked Oct 28 '17 22:10

ajayramesh


People also ask

How do you select a specific value in a DataFrame?

Select Data Using Location Index (. This means that you can use dataframe. iloc[0:1, 0:1] to select the cell value at the intersection of the first row and first column of the dataframe. You can expand the range for either the row index or column index to select more data.


1 Answers

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

like image 59
piRSquared Avatar answered Oct 30 '22 09:10

piRSquared