首页 > 解决方案 > 在一级减去不匹配索引器的 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中不存在的价值。MidTimeStampaamov3Movieb

我正在尝试减去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

这确实会返回所需的系列,但在大型数据集上会花费太长时间并且不是很“漂亮”。

我想知道是否有更好的解决方案。

标签: pythonpandas

解决方案


推荐阅读