Change the item in the last row of the DataFrame

I set a simple DataFrame in pandas:

a = pandas.DataFrame([[1,2,3], [4,5,6], [7,8,9]], columns=['a','b','c']) >>> print a abc 0 1 2 3 1 4 5 6 2 7 8 9 

I would like to be able to change one item on the last line. In pandas == 0.13.1, I could use the following:

 a.iloc[-1]['a'] = 77 >>> print a abc 0 1 2 3 1 4 5 6 2 77 8 9 

but after upgrading to pandas == 0.14.1, I get the following warning while doing this:

 SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_index,col_indexer] = value instead 

The problem, of course, is that -1 is not an index of a , so I cannot use loc . As the warning shows, I did not change the 'a' column of the last row, I only changed the discarded local copy.

How to do this in the new version of pandas? I understand that I can use the index of the last line, for example:

 a.loc[2,'a'] = 77 

But I will work with tables where several rows have the same index, and I do not want to reindex my table every time. Is there any way to do this without knowing the index of the last line before hand?

+6
source share
3 answers

Well, I found a way to solve this problem without a chain and not worry about a few indicators.

 a.iloc[-1, a.columns.get_loc('a')] = 77 >>> a abc 0 1 2 3 1 4 5 6 2 77 8 9 

I could not use iloc because I could not provide the column index as int, but get_loc solves this problem. Thanks for the helpful comments to everyone!

+4
source

For pandas 0.22,

 a.at[a.index[-1], 'a'] = 77 

this is just one way.

0
source

Taking elements from @PallavBakshi and @Mike solutions, in Pandas> = 0.19

Just using iloc [-1, 'a] will not work, since -1 is not in the index.

 a.loc[a.index[-1], 'a']= 4.0 
0
source

Source: https://habr.com/ru/post/973417/


All Articles