Set value for particular cell in pandas DataFrame using index

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

    .iat/.at is the good solution. Supposing you have this simple data_frame:

       A   B   C
    0  1   8   4 
    1  3   9   6
    2  22 33  52
    

    if we want to modify the value of the cell [0,"A"] u can use one of those solution :

    1. df.iat[0,0] = 2
    2. df.at[0,'A'] = 2

    And here is a complete example how to use iat to get and set a value of cell :

    def prepossessing(df):
      for index in range(0,len(df)): 
          df.iat[index,0] = df.iat[index,0] * 2
      return df
    

    y_train before :

        0
    0   54
    1   15
    2   15
    3   8
    4   31
    5   63
    6   11
    

    y_train after calling prepossessing function that iat to change to multiply the value of each cell by 2:

         0
    0   108
    1   30
    2   30
    3   16
    4   62
    5   126
    6   22
    

提交回复
热议问题