Python: create new column and copy value from other row which is a swap of current row

Viewed 34

I have a dataframe which has 3 columns:

import pandas as pd

d = {'A':  ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]}

df = pd.DataFrame(d)

Dataframe looks like this:

  A       B   VALUE
left    right   0
right   left    1
east    west    2
west    east    3
south   north   4
north   south   5

I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.

Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:

  A       B   VALUE VALUE_2
left    right   0     1
right   left    1     0
east    west    2     3
west    east    3     2
south   north   4     5
north   south   5     4

I tried:

for row_num, record in df.iterrows():
    A = df['A'][index]
    B = df['B'][index]
    if(pd.Series([record['A'] == B, record['B'] == A).all()):
        df['VALUE_2'] = df['VALUE']

I'm struck here, inputs will be highly appreciated.

2 Answers

Use map by Series:

df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
print (df)
       A      B  VALUE  VALUE_2
0   left  right      0        1
1  right   left      1        0
2   east   west      2        3
3   west   east      3        2
4  south  north      4        5
5  north  south      5        4

Just a more verbose answer:

import pandas as pd

d = {'A':  ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]}

df = pd.DataFrame(d)

pdf = pd.DataFrame([])
for idx, item in df.iterrows():
    indx = list(df['B']).index(str(df['A'][idx]))
    pdf = pdf.append(pd.DataFrame({'VALUE_2': df.iloc[indx][2]}, index=[0]), ignore_index=True)

print(pdf)
data = pd.concat([df, pdf], axis=1)
print(data)
Related