What is correct syntax to swap column values for selected rows in a pandas data frame using just one line?

前端 未结 3 970
说谎
说谎 2020-12-24 14:33

I am using pandas version 0.14.1 with Python 2.7.5, and I have a data frame with three columns, e.g.:

import pandas as pd

d = {\'L\':  [\'left\', \'right\',         


        
3条回答
  •  执念已碎
    2020-12-24 14:41

    The key thing to note here is that pandas attempts to automatically align rows and columns using the index and column names. Hence, you need to somehow tell pandas to ignore the column names here. One way is as @DSM does, by converting to a numpy array. Another way is to rename the columns:

    >>> df.loc[idx] = df.loc[idx].rename(columns={'R':'L','L':'R'})
    
          L      R  VALUE
    0  left  right     -1
    1  left  right      1
    2  left  right     -1
    3  left  right      1
    4  left  right     -1
    5  left  right      1
    

提交回复
热议问题