Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
190 views
in Technique[技术] by (71.8m points)

python - Change an element in the last row of a DataFrame

I set up a simple DataFrame in pandas:

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

I would like to be able to alter a single element in the last row of. In pandas==0.13.1 I could use the following:

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

but after updating to pandas==0.14.1, I get the following warning when 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 being that -1 is not an index of a, so I can't use loc. As the warning indicates, I have not changed column 'a' of the last row, I've only altered a discarded local copy.

How do I do this in the newer version of pandas? I realize I could use the index of the last row like:

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

But I'll be working with tables where multiple rows have the same index, and I don't want to reindex my table every time. Is there a way to do this without knowing the index of the last row before hand?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Alright I've found a way to solve this problem without chaining, and without worrying about multiple indices.

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

I wasn't able to use iloc before because I couldn't supply the column index as an int, but get_loc solves that problem. Thanks for the helpful comments everyone!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...