将宽柱重塑为长柱

2024-04-29 09:58:21 发布

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

我有一个像下面这样的大熊猫

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

现在的情况是我将两个不同团队之间的内部事务分离为两个不同事务中的一个。你知道吗

我试着用df.unstack()并且读了this answer我不知道如何告诉熊猫我想要解开它。你知道吗

更新1:

问题的大背景是:

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)条件就不能应用

我希望我介绍南的意图是明确的。你知道吗


Tags: 类型情况nan团队qtyt1t2tno
1条回答
网友
1楼 · 发布于 2024-04-29 09:58:21

如果可能,团队的一个输出列使用^{}

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

编辑:如果只有两个团队可以将^{}^{}一起使用,则相同列顺序的last使用^{}和last ^{}

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

相关问题 更多 >