Set value for particular cell in pandas DataFrame using index

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

    Here is a summary of the valid solutions provided by all users, for data frames indexed by integer and string.

    df.iloc, df.loc and df.at work for both type of data frames, df.iloc only works with row/column integer indices, df.loc and df.at supports for setting values using column names and / or integer indices.

    When the specified index does not exist, both df.loc and df.at would append the newly inserted rows/columns to the existing data frame, but df.iloc would raise "IndexError: positional indexers are out-of-bounds". A working example tested in Python 2.7 and 3.7 is as follows:

    import numpy as np, pandas as pd
    
    df1 = pd.DataFrame(index=np.arange(3), columns=['x','y','z'])
    df1['x'] = ['A','B','C']
    df1.at[2,'y'] = 400
    
    # rows/columns specified does not exist, appends new rows/columns to existing data frame
    df1.at['D','w'] = 9000
    df1.loc['E','q'] = 499
    
    # using df[] ==  to retrieve target rows
    df1.at[df1['x']=='B', 'y'] = 10000
    df1.loc[df1['x']=='B', ['z','w']] = 10000
    
    # using a list of index to setup values
    df1.iloc[[1,2,4], 2] = 9999
    df1.loc[[0,'D','E'],'w'] = 7500
    df1.at[[0,2,"D"],'x'] = 10
    df1.at[:, ['y', 'w']] = 8000
    
    df1
    >>> df1
         x     y     z     w      q
    0   10  8000   NaN  8000    NaN
    1    B  8000  9999  8000    NaN
    2   10  8000  9999  8000    NaN
    D   10  8000   NaN  8000    NaN
    E  NaN  8000  9999  8000  499.0
    

提交回复
热议问题