首页 > 解决方案 > Python:创建新列并从其他行复制值,这是当前行的交换

问题描述

我有一个包含 3 列的数据框:

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)

数据框如下所示:

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

我正在尝试创建一个新列 VALUE_2,它应该包含同一数据框中交换行的值。

例如:右 - 左值为 0,左 - 右值为 1,我希望新列中的交换值如下所示:

  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

我试过了:

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']

我在这里感到震惊,我们将不胜感激。

标签: python-3.xpandas

解决方案


使用者:map_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

推荐阅读