Set value for particular cell in pandas DataFrame using index

后端 未结 20 1851
野趣味
野趣味 2020-11-22 05:45

I\'ve created a Pandas DataFrame

df = DataFrame(index=[\'A\',\'B\',\'C\'], columns=[\'x\',\'y\'])

and got this

    x    y
A  NaN         


        
20条回答
  •  無奈伤痛
    2020-11-22 06:43

    set_value() is deprecated.

    Starting from the release 0.23.4, Pandas "announces the future"...

    >>> df
                       Cars  Prices (U$)
    0               Audi TT        120.0
    1 Lamborghini Aventador        245.0
    2      Chevrolet Malibu        190.0
    >>> df.set_value(2, 'Prices (U$)', 240.0)
    __main__:1: FutureWarning: set_value is deprecated and will be removed in a future release.
    Please use .at[] or .iat[] accessors instead
    
                       Cars  Prices (U$)
    0               Audi TT        120.0
    1 Lamborghini Aventador        245.0
    2      Chevrolet Malibu        240.0
    

    Considering this advice, here's a demonstration of how to use them:

    • by row/column integer positions

    >>> df.iat[1, 1] = 260.0
    >>> df
                       Cars  Prices (U$)
    0               Audi TT        120.0
    1 Lamborghini Aventador        260.0
    2      Chevrolet Malibu        240.0
    
    • by row/column labels

    >>> df.at[2, "Cars"] = "Chevrolet Corvette"
    >>> df
                      Cars  Prices (U$)
    0               Audi TT        120.0
    1 Lamborghini Aventador        260.0
    2    Chevrolet Corvette        240.0
    

    References:

    • pandas.DataFrame.iat
    • pandas.DataFrame.at

提交回复
热议问题