python - Python数据框连接选择不存在的地方
问题描述
我下面有 2 个数据框我想设置 NxtCase 值
dfObj = pd.DataFrame(columns=['ID', 'Case','NxtCase'])
dfObj = dfObj.append({'ID': 11234, 'Case': 'A', 'NxtCase': ''}, ignore_index=True)
dfObj = dfObj.append({'ID': 2347, 'Case': 'C', 'NxtCase': ''}, ignore_index=True)
dfObj = dfObj.append({'ID': 31278, 'Case': 'E', 'NxtCase': ''}, ignore_index=True)
dfObj2 = pd.DataFrame(columns=['ID', 'Case'])
dfObj2 = dfObj2.append({'ID': 11234, 'Case': 'A' }, ignore_index=True)
dfObj2 = dfObj2.append({'ID': 11234, 'Case': 'B'}, ignore_index=True)
dfObj2 = dfObj2.append({'ID': 2347, 'Case': 'C'}, ignore_index=True)
dfObj2 = dfObj2.append({'ID': 2347, 'Case': 'D'}, ignore_index=True)
dfObj2 = dfObj2.append({'ID': 31278, 'Case': 'E'}, ignore_index=True)
dfObj2 = dfObj2.append({'ID': 31278, 'Case': 'F'}, ignore_index=True)
print(dfObj)
print(dfObj2)
我的目标是将 dfObj 与 dfObj2 进行比较并设置 NxtCase 值。
NxtCase 值必须等于基于 ID 的缺失字母 Case,而不是 Case 列中当前存在的内容。
例如 ID =1 和 Case= 'A' 然后值 NxtCase = 'B' 关于如何设置此值的任何想法?
例如这里是我所拥有的样本
ID Case NxtCase
11234 A
2347 C
31278 E
这是我想要的结果
ID Case NxtCase
11234 A B
2347 C D
31278 E F
我认为这很容易,我可能只是没有正确解释它。我不是很精通python,但我可以做到这一点是SQL。最终的选择表是我试图在 python 中完成的
Create table #tmp1(
ID int,
[Case] varchar(20),
[NxtCase] varchar(20)
)
Create table #tmp2(
ID int,
[Case] varchar(20),
)
Insert into #tmp1(ID,[Case])
Select 23, 'A'
Union
Select 51, 'H'
Union
Select 63, 'L'
Insert into #tmp2(ID,[Case])
Select 23, 'A'
Union
Select 51, 'H'
Union
Select 63, 'L'
union
Select 23, 'D'
Union
Select 51, 'O'
Union
Select 63, 'E'
update t1
Set [NxtCase] = t2.[Case]
from #tmp1 t1
join #tmp2 t2
on t1.ID = t2.ID
and t1.[Case] <> t2.[Case]
Select * from #tmp1
解决方案
解决方案:
dfObj['NxtCase'] = dfObj.apply(lambda row:dfObj2[dfObj2['ID'] == row['ID']][dfObj2['Case']!=row['Case']]['Case'], axis =1).fillna(method='bfill',axis=1).iloc[:, 0]
此处发布的完整问题解决方案: https ://www.experts-exchange.com/questions/29198267/Python-dataframe-join-select-where-not-exists.html#questionAdd
推荐阅读
- react-native - setState 挂钩未更新 - 尽管 prevState 显示正确的值
- object - 如何解决未定义对象的 TypeError
- c# - 从 C# 表单中搜索两个访问表
- firebase - 单独使用 Google Identity Platform + Firebase Auth
- javascript - 有没有办法在 firefox 扩展和 node.js 程序之间发送数据?
- laravel - Laravel 8 Multi Auth with Jetstream livewire
- sql - 使用空值加入和最大日期
- amazon-web-services - AWS 无服务器图像处理程序错误处理
- javascript - 展开所有文本区域,无需单击每个区域
- c++ - CMake find_package 用于非标准位置