Set value for particular cell in pandas DataFrame using index

后端 未结 20 1973
野趣味
野趣味 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:46

    I tested and the output is df.set_value is little faster, but the official method df.at looks like the fastest non deprecated way to do it.

    import numpy as np
    import pandas as pd
    
    df = pd.DataFrame(np.random.rand(100, 100))
    
    %timeit df.iat[50,50]=50 # ✓
    %timeit df.at[50,50]=50 #  ✔
    %timeit df.set_value(50,50,50) # will deprecate
    %timeit df.iloc[50,50]=50
    %timeit df.loc[50,50]=50
    
    7.06 µs ± 118 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    5.52 µs ± 64.2 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    3.68 µs ± 80.8 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
    98.7 µs ± 1.07 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    109 µs ± 1.42 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)
    

    Note this is setting the value for a single cell. For the vectors loc and iloc should be better options since they are vectorized.

提交回复
热议问题