How to update values in a specific row in a Python Pandas DataFrame?

后端 未结 4 1342
猫巷女王i
猫巷女王i 2020-12-02 12:09

With the nice indexing methods in Pandas I have no problems extracting data in various ways. On the other hand I am still confused about how to change data in an existing Da

4条回答
  •  广开言路
    2020-12-02 13:04

    So first of all, pandas updates using the index. When an update command does not update anything, check both left-hand side and right-hand side. If for some reason you are too lazy to update the indices to follow your identification logic, you can do something along the lines of

    >>> df.loc[df.filename == 'test2.dat', 'n'] = df2[df2.filename == 'test2.dat'].loc[0]['n']
    >>> df
    Out[331]: 
        filename   m     n
    0  test0.dat  12  None
    1  test2.dat  13    16
    

    If you want to do this for the whole table, I suggest a method I believe is superior to the previously mentioned ones: since your identifier is filename, set filename as your index, and then use update() as you wanted to. Both merge and the apply() approach contain unnecessary overhead:

    >>> df.set_index('filename', inplace=True)
    >>> df2.set_index('filename', inplace=True)
    >>> df.update(df2)
    >>> df
    Out[292]: 
                m     n
    filename           
    test0.dat  12  None
    test2.dat  13    16
    

提交回复
热议问题