python - 在一级减去不匹配索引器的 pd 系列
问题描述
我正在尝试减去两个具有相同级别的 MultiIndexed 的 pd.Series,在级别值中部分匹配:
a = pd.DataFrame({'Subject':['S1', 'S1', 'S1', 'S1', 'S2', 'S2', 'S2', 'S2', 'S3', 'S3', 'S3', 'S3', 'S3', 'S3'],
'Movie':['mov1', 'mov1', 'mov2', 'mov2', 'mov1', 'mov1', 'mov2', 'mov2', 'mov1', 'mov1', 'mov2', 'mov2', 'mov3', 'mov3'],
'TimeStamp':['Start', 'End', 'Start', 'End', 'Start', 'End', 'Start', 'End', 'Start', 'End', 'Start', 'End', 'Start', 'End'],
'Distance': np.random.rand(14)*100}).set_index(['Subject', 'Movie', 'TimeStamp'])['Distance']
b = pd.DataFrame({'Subject':['S1', 'S1', 'S1', 'S1', 'S1', 'S2', 'S2', 'S2', 'S2', 'S3', 'S3', 'S3', 'S3', 'S3', 'S3'],
'Movie':['mov1', 'mov1', 'mov2', 'mov2', 'mov2', 'mov1', 'mov1', 'mov2', 'mov2', 'mov1', 'mov1', 'mov1', 'mov2', 'mov2', 'mov2'],
'TimeStamp':['Start', 'End', 'Start', 'Mid', 'End', 'Start', 'End', 'Start', 'End', 'Start', 'Mid', 'End','Start', 'Mid', 'End'],
'Distance': np.random.rand(15)*100}).set_index(['Subject', 'Movie', 'TimeStamp'])['Distance']
Note在 level中b
的值在;中不存在。另一方面,在 level中不存在的价值。Mid
TimeStamp
a
a
mov3
Movie
b
我正在尝试减去b.subtract(a, level=['Subject', 'Movie', 'TimeStamp'])
,但由于TypeError: Join on level between two MultiIndex objects is ambiguous
.
一种可能的解决方案是创建两个 Series 的副本并使用以下内容填充缺失值0
:
index_in_a_not_in_b = set(a.index) - set(b.index)
index_in_b_not_in_a = set(b.index) - set(a.index)
a = a.append(pd.Series([0 for item in index_in_b_not_in_a], index=index_in_b_not_in_a)).sort_index()
b = b.append(pd.Series([0 for item in index_in_a_not_in_b], index=index_in_a_not_in_b)).sort_index()
b.subtract(a, level=['Subject', 'Movie', 'TimeStamp'])
>> out:
Subject Movie TimeStamp
S1 mov1 End 27.127491
Start 18.366840
mov2 End 13.320173
Mid 72.190967
Start 14.303218
S2 mov1 End 0.892581
Start 11.854033
mov2 End -36.461281
Start 91.406533
S3 mov1 End -62.710614
Mid 96.432693
Start -35.638531
mov2 End -91.539902
Mid 25.313664
Start 21.362349
mov3 End -79.483691
Start -3.146545
dtype: float64
这确实会返回所需的系列,但在大型数据集上会花费太长时间并且不是很“漂亮”。
我想知道是否有更好的解决方案。
解决方案
推荐阅读
- java - 在 Kubernetes 中找不到客户端会话 ID
- java - Apk 未正确构建
- deployment - DigitalOcean - 在预编译资产上限制登台部署错误
- java - 在 SpringSecurity 中未调用自定义 UserDetailsService Impl
- sql - sqlopenresult' status='-239' / cognos 报错
- python - GloVe 文本摘要返回停用词乱码
- c# - 从 Child UserControl WPF 更改父 UserControl 中的文本
- kubernetes - Kubernetes 用户界面仪表板
- javascript - 尽管在 main.js 之前加载了 jquery,但未定义 jquery $
- sed - 使用 sed 提取 /dev/nvme0 设备的 UUID