python-3.x - 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']
我在这里感到震惊,我们将不胜感激。
解决方案
使用者: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
推荐阅读
- scala - Alpakka S3 从存储桶下载文件,保存到文件,并为流程的下一部分提供文件名
- r - 使用 `data.table` 的 DT[ i , j, by] 时,是否可以预先设置列类型?
- c# - MSBuild 项可以使用由目标设置的属性吗?
- r - XML->列表-> R中具有可变结构的数据框
- java - GSON java.lang.IllegalArgumentException:类 android.widget.TextView 声明了多个名为 mMinWidth 的 JSON 字段
- python-3.x - Pyspark 自定义转换链接
- javascript - 猫鼬文本搜索不返回任何结果
- cname - 一个子域可以有不同的 CNAME 记录,还是整个域必须有相同的 CNAME?
- python-3.x - 这个语法在 Python 3 中是什么意思?
- node.js - 使用渲染时将标头发送到客户端后无法设置标头