Change an element in the last row of a DataFrame

后端 未结 3 1016
闹比i
闹比i 2021-01-01 16:49

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条回答
  • 2021-01-01 17:33

    For pandas 0.22,

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

    this is just one of the ways.

    0 讨论(0)
  • 2021-01-01 17:44

    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!

    0 讨论(0)
  • 2021-01-01 17:53

    Taking elements from the solutions of @PallavBakshi and @Mike, the following works in Pandas >= 0.19

    Just using iloc[-1, 'a] won't work as -1 is not in the index.

    a.loc[a.index[-1], 'a']= 4.0
    
    0 讨论(0)
提交回复
热议问题