簡體   English   中英

在熊貓數據框中轉換列,同時保持其他列完整無缺

[英]Transposing a column in a pandas dataframe while keeping other column intact with duplicates

我的數據框如下

selection_id  last_traded_price
430494        1.46
430494        1.48
430494        1.56
430494        1.57
430495        2.45
430495        2.67
430495        2.72
430495        2.87

我有很多包含選擇ID的行,我需要保持selection_id列不變,但將數據按最后交易價格進行轉置,如下所示。

selection_id  last_traded_price
430494        1.46              1.48          1.56      1.57    e.t.c 
430495        2.45              2.67          2.72      2.87    e.t.c

我嘗試過使用樞軸

   (df.pivot(index='selection_id', columns=last_traded_price', values='last_traded_price')

由於selection_id中存在重復的行,因此數據透視不起作用。 是否可以先轉置數據然后將重復的數據刪除?

選項1
groupby + apply

v = df.groupby('selection_id').last_traded_price.apply(list)
pd.DataFrame(v.tolist(), index=v.index)

                 0     1     2     3
selection_id                        
430494        1.46  1.48  1.56  1.57
430495        2.45  2.67  2.72  2.87

選項2
可以使用pivot進行此操作,只要您還有另一列要傳遞的計數即可(這就是為什么它需要沿某些方向旋轉)。

df['Count'] = df.groupby('selection_id').cumcount()
df.pivot('selection_id', 'Count', 'last_traded_price')

Count            0     1     2     3
selection_id                        
430494        1.46  1.48  1.56  1.57
430495        2.45  2.67  2.72  2.87

您可以使用cumcount的櫃台通過創建新列名set_index + unstackpandas.pivot

g = df.groupby('selection_id').cumcount()
df = df.set_index(['selection_id',g])['last_traded_price'].unstack()
print (df)
                 0     1     2     3
selection_id                        
430494        1.46  1.48  1.56  1.57
430495        2.45  2.67  2.72  2.87

pivot類似的解決方案:

df = pd.pivot(index=df['selection_id'], 
              columns=df.groupby('selection_id').cumcount(), 
              values=df['last_traded_price'])
print (df)
                 0     1     2     3
selection_id                        
430494        1.46  1.48  1.56  1.57
430495        2.45  2.67  2.72  2.87

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM