在pandas中添加具有重复索引的行

2024-10-01 05:05:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组“单向”的航空公司数据,有点像下面(数字不是连续的,或者实际数据中每一行的数字都是相同的):

origin dest    a  b  c  d  e  f
BOS    JFK     1  2  3  4  5  6
       DCA     1  2  3  4  5  6
JFK    BOS     1  2  3  4  5  6
       DCA     1  2  3  4  5  6
DCA    BOS     1  2  3  4  5  6
       JFK     1  2  3  4  5  6

我想得到“多向”数据,即如下所示:

^{pr2}$

我一直在尝试使用pivot表,但到目前为止还没有找到任何远程有用的解决方案。在


Tags: 数据远程数字origin解决方案destpivot单向
2条回答

这就是你想要的吗?在

In [133]: df.groupby('dest').sum().reset_index()
Out[133]:
  dest  a  b  c  d   e   f
0  BOS  2  4  6  8  10  12
1  DCA  2  4  6  8  10  12
2  JFK  2  4  6  8  10  12

您可以先按行对origindest列进行排序,然后执行groupbysum,因为结果看起来并不关心origin和{}的顺序:

import pandas as pd

df.reset_index(["origin", "dest"])
od = df.loc[:,'origin':'dest'].as_matrix()
od.sort()
df[['air1','air2']] = pd.DataFrame(od)
df.groupby(['air1','air2']).sum()

            a   b   c   d   e   f
air1 air2                       
BOS  DCA    2   4   6   8   10  12
     JFK    2   4   6   8   10  12
DCA  JFK    2   4   6   8   10  12

相关问题 更多 >