重塑熊猫宽柱长

时间:2017-07-12 05:17:20

标签: python pandas

我有一个像下面的熊猫dv

tno,tdate,buyprice,sellprice,qty,t1,t2
1,2017,10,20,5,teamA,teamB
2,2017,5,10,5,teamB,teamA

预期的操作:

tno,tdate,buyprice,sellprice,qty,t1,t2
1,2017,10,20,5,teamA,NaN
1,2017,10,20,5,NaN,teamB
2,2017,5,10,5,teamB,NaN
2,2017,5,10,5,NaN,TeamA

发生的事情是我将2个不同团队之间的内部交易分成2个不同的交易。

我尝试使用df.unstack()并阅读this answer我错过了告诉大熊猫我想要取消它的方式的方法。

UPDATE1:

问题的更大背景是:

tno,tdate,buyprice,sellprice,qty,Buyerteam,Sellerteam
1,2017,10,20,5,teamA,teamB
2,2017,5,10,5,teamB,teamA

有两种类型的交易

  1. 类型1。 Buyerteam = NaN或Sellerteam = NaN(从不两者) 我计算qty*(buyprice or sell price)来计算团队的开支。如果buyTeam是NaN,我会qty*sellpriceif sellTeam=NaN I do qty*buyprice
  2. 2型。其中t1和t2都不是NaN(本问题中的情况) 我正在努力将type2数据转换为type1数据。但如果我不介绍NaN,我qty*(buyprice or sellprice)的条件无法应用
  3. 我希望我引入NaN的意图很明确。

1 个答案:

答案 0 :(得分:0)

如果可能,团队的一个输出列使用lreshape

df = pd.lreshape(df, {'t':['t1','t2']})
print (df)
   buyprice  sellprice  tdate  tno      t
0        10         20   2017    1  teamA
1         5         10   2017    2  teamB
2        10         20   2017    1  teamB
3         5         10   2017    2  teamA

编辑:如果只有2个团队可以使用concat drop,则使用reindex_axissort_values使用最后一列:

df = pd.concat([df.drop('t2', axis=1), df.drop('t1', axis=1)], ignore_index=True)
       .reindex_axis(df.columns, 1)
       .sort_values(['tno','tdate'])
print (df)
   tno  tdate  buyprice  sellprice     t1     t2
0    1   2017        10         20  teamA    NaN
2    1   2017        10         20    NaN  teamB
1    2   2017         5         10  teamB    NaN
3    2   2017         5         10    NaN  teamA
相关问题