amiref
amiref

Reputation: 3441

Setting a value to a cell in a pandas dataframe

I have the following pandas dataframe:

K = pd.DataFrame({"A":[1,2,3,4], "B":[5,6,7,8]})

Then I set the cell in the first row and first column to 11:

K.iloc[0]["A"] = 11

And when I check the dataframe again, I see that the value assignment is done and K.iloc[0]["A"] is equal to 11. However when I add a column to this data frame and do the same operation for a cell in the new column, the value assignment is not successful:

K["C"] = 0
K.iloc[0]["C"] = 11

So, when I check the dataframe again, the value of K.iloc[0]["C"] is still zero. I appreciate if somebody can tell me what is going on here and how I can resolve this issue.

Upvotes: 0

Views: 73

Answers (4)

Sajan
Sajan

Reputation: 1267

loc should work :

K.loc[0]['C'] = 11
K.loc[0, 'C'] = 11

Both the above versions of loc will be able to assign values to the dataframe K.

Upvotes: 2

jezrael
jezrael

Reputation: 863791

If default index, RangeIndex is possible use DataFrame.loc, but it set index values by label 0 (what is same like position 0):

K['C'] = 0
K.loc[0, ["A", "C"]] = 11
print (K)
    A  B   C
0  11  5  11
1   2  6   0
2   3  7   0
3   4  8   0

Reason why your solution failed is possible find in docs:

This can work at times, but it is not guaranteed to, and therefore should be avoided:

dfc['A'][0] = 111

Solution with DataFrame.iloc is possible with get positions of columns by Index.get_indexer:

print (K.columns.get_indexer(["A", "C"]))
[0 2]

K['C'] = 0
K.iloc[0, K.columns.get_indexer(["A", "C"])] = 11
print (K)
    A  B   C
0  11  5  11
1   2  6   0
2   3  7   0
3   4  8   0

Upvotes: 2

Guilhem L.
Guilhem L.

Reputation: 421

When you use K.iloc[0]["C"], you first take the first line, so you have a copy of a slice from your dataframe, then you take the column C. So you change the copy from the slice, not the original dataframe.

That your first call, K.iloc[0]["A"] = 11 worked fine was in some sens a luck.

The good habit is to use loc in "one shot", so you have access to the original value of the dataframe, not on a slice copy :

K.loc[0,"C"] = 11

Be careful that iloc and loc are different function, even if they seems quite similar here.

Upvotes: 2

roarkz
roarkz

Reputation: 831

For simplicity, I would do the operations in a different order and use loc:

K.loc[0, 'C'] = 0
K.loc[0, ['A', 'C']] = 11

Upvotes: 3

Related Questions