Set value for particular cell in pandas DataFrame using index

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

    One way to use index with condition is first get the index of all the rows that satisfy your condition and then simply use those row indexes in a multiple of ways

    conditional_index = df.loc[ df['col name']  ].index
    

    Example condition is like

    ==5, >10 , =="Any string", >= DateTime
    

    Then you can use these row indexes in variety of ways like

    1. Replace value of one column for conditional_index
    df.loc[conditional_index , [col name]]= 
    
    1. Replace value of multiple column for conditional_index
    df.loc[conditional_index, [col1,col2]]= 
    
    1. One benefit with saving the conditional_index is that you can assign value of one column to another column with same row index
    df.loc[conditional_index, [col1,col2]]= df.loc[conditional_index,'col name']
    

    This is all possible because .index returns a array of index which .loc can use with direct addressing so it avoids traversals again and again.

提交回复
热议问题