Search code examples
pythonpandasdataframecomparisonlatitude-longitude

Comparing two rows and changing depending on values


I have a pandas dataframe of longitudes and their corresponding "E" and "W" values. The longitudes and their corresponding values are in the same dataframe but are within two different columns.

I am trying to evaluate column 2, so that when the value is "E" my corresponding longitude (in column 1), will be positive and when the value is "W" the value will become negative.

Please see below for an example dataframe.

index   column 1       column 2 
0    71.33435833333333   W
1    71.334355           W
2    71.33435833333333   W
3    71.33436166666667   W
4    71.33436166666667   W
5    71.33425            E
6    71.33392166666667   E
7    71.33434166666666   E

Any help would be greatly appreciated. If more information is needed about the problem, please let me know.


Solution

  • IIUC, you can use slicing for in place modification:

    df.loc[df['column 2'].eq('W'), 'column 1'] *= -1
    

    output:

       index   column 1 column 2
    0      0 -71.334358        W
    1      1 -71.334355        W
    2      2 -71.334358        W
    3      3 -71.334362        W
    4      4 -71.334362        W
    5      5  71.334250        E
    6      6  71.333922        E
    7      7  71.334342        E