python - 熊猫:来自不同行的相等值
问题描述
数据框示例:
A B
0 2.234560 0.842407
1 0.842407 2.234560
2 3.183770 1.200300
3 1.200300 3.18377
我正在尝试添加一个关于“A”和“B”列中的值匹配的新列
像这样:
A B C
0 2.234560 0.842407 A0 Matching with B1
1 0.842407 2.234560 B1 Matching with A0
2 3.183770 1.200300 A2 Matching with B3
3 1.200300 3.183770 B3 Matching with A2
什么是正确的解决方案?
解决方案
一些步骤可以改进,但应该有效:
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(4,1), columns=['A'])
df['B'] = df['A'].sample(frac=1).reset_index(drop=True)
df_temp_a = df[['A']].assign(col_string_a = lambda x: 'A'+x.index.astype('str')).set_index('A')
df_temp_b = df[['B']].assign(col_string_b = lambda x: 'B'+x.index.astype('str')).set_index('B')
merged = df_temp_a.join(df_temp_b, how='inner')
merged['final_col'] = merged['col_string_a'] + " Matching with " + merged['col_string_b']
merged
df.merge(merged[['final_col']], how='left', left_on=['A'], right_index=True)
推荐阅读
- python - 来自 scikit-learn 的 FutureWarning get_params
- javascript - 使用 k6 JSON 输出生成 html 报告
- jquery - 对象不支持此操作 Web 音频 API 未在 Internet Explorer 中加载
- javascript - 访问和修改服务器端高分文件的正确方法是什么?
- javascript - Firefox、chrome、edge 不支持 Xml.TransformNode(xmldoc)
- android - 将对象附加到 Arcore 相机
- python - Python:使用 .grid() 用 5 列填充整个框架宽度
- css - 如何找出哪些 SCSS 文件导致了特定的 CSS 设置
- python - 将密钥发送到后台应用程序
- r - 在 PSM(R 的 Matchit 包)中使用卡尺会改变匹配并使平衡变得更糟,即使匹配处理的数量保持不变?