我有代表人们跨越国界的DataFrame流

flows = DataFrame([[1,2],[3,4]], index=['Monday', 'Tuesday'], columns=['CZ>DE', 'HU>AT'])

         CZ>DE  HU>AT
Monday       1      2
Tuesday      3      4


我想将每列分为代表国家/地区每边界增减的两列。我当前的代码和期望的结果是这样的

country_from = lambda x: x[:2]
country_to = lambda x: x[3:]
flows_from = -1*flows.copy()
flows_from.columns = pd.MultiIndex.from_tuples([(border, country_from(border)) for border in flows.columns])
flows_to = flows.copy()
flows_to.columns = pd.MultiIndex.from_tuples([(border, country_to(border)) for border in flows.columns])
country_flows = pd.concat([flows_from, flows_to], axis=1)
country_flows = country_flows.groupby(level=[0,1], axis=1).sum()

           CZ>DE    HU>AT
           CZ DE    AT HU
Monday     -1  1     2 -2
Tuesday    -3  3     4 -4


该解决方案非常冗长,我怀疑它可以做得更好。会有一个主意吗?

最佳答案

您可以创建元组来定义MultiIndex的级别:

tuples = [(i,k) for i, j in zip(flows.columns,[i.split('>') for i in flows.columns]) for k in j]

x = flows.values


然后:

data = np.multiply(np.tile([-1,1], x.shape), np.repeat(x, 2, axis=1))

pd.DataFrame(data=data, index=flows.index, columns=pd.MultiIndex.from_tuples(tuples))


产量:

        CZ>DE    HU>AT
           CZ DE    HU AT
Monday     -1  1    -2  2
Tuesday    -3  3    -4  4

10-04 13:16