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

时间:2016-06-23 22:31:28

标签: python pandas pivot-table

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

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

我想得到"多向"数据,如下所示:

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

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

2 个答案:

答案 0 :(得分:1)

是你想要的吗?

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

答案 1 :(得分:0)

您可以先按行对origindest列进行排序,然后执行groupbysum,因为看起来您的结果并不在乎关于origindest

的顺序
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