2017-07-12 31 views
0

我有一个熊猫DF像下面重塑熊猫宽列长

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

预计OP:

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 

有2种类型的交易

  1. 类型1的。其中Buyerteam = NaN或Sellerteam = NaN(从未同时) ,我计算qty*(buyprice or sell price)来计算团队的支出。如果buyTeam是NaN,我做qty*sellpriceif sellTeam=NaN I do qty*buyprice
  2. Type2。其中t1和t2不是NaN(在这个问题中的情况) 我amtrying将type2数据转换为type1数据。但如果我不介绍NaN,我的qty*(buyprice or sellprice)的条件不能应用

我希望我介绍NaN的意图很明确。

+0

是否有可能为所有团队输出一列? – jezrael

+0

为问题添加了一些细节 – pythonRcpp

+0

对不起,我当时离线。但我想帮助你,虽然更好的是以这种方式创造新的问题。您是否可以更改所需输出的数据样本以获得更好的解释并更好地验证我的或其他解决方案? – jezrael

回答

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支球队有可能使用concatdrop,持续列相同的次序使用reindex_axis和最后sort_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