簡體   English   中英

使用 Pandas 將列索引堆疊在一起

[英]Stacking column indices on top of one another using Pandas

我希望將一些列的索引堆疊在一起,這就是我目前擁有的:

                          
            Buy     Buy Currency   Sell     Sell Currency   
Date                        
2013-12-31  100     CAD            100      USD
2014-01-02  200     USD            200      CAD
2014-01-03  300     CAD            300      USD
2014-01-06  400     USD            400      CAD

這就是我想要實現的目標:

Buy/Sell     Buy/Sell Currency   
                     

100          USD
100          CAD
200          CAD
200          USD
300          USD
300          CAD

依此類推,基本上想要獲取“買入”和“買入貨幣”中的值,並將它們的值一個接一個地堆疊在“賣出”和“賣出貨幣”列中。

等等。 我應該提到我的數據框總共有 10 列,所以使用

df_pl.stack(level=0)

似乎不起作用。

一種選擇是使用pyjanitor中的pivot_longer ,對於這個特定的用例,您傳遞一個正則表達式列表(到names_pattern )以將所需的列標簽聚合到新組中(在names_to中):

# pip install pyjanitor
import pandas as pd
import janitor

df.pivot_longer(index=None, 
                names_to = ['Buy/Sell', 'Buy/Sell Currency'], 
                names_pattern = [r"Buy$|Sell$", ".+Currency$"], 
                ignore_index = False, 
                sort_by_appearance=True)

            Buy/Sell Buy/Sell Currency
Date                                  
2013-12-31       100               CAD
2013-12-31       100               USD
2014-01-02       200               USD
2014-01-02       200               CAD
2014-01-03       300               CAD
2014-01-03       300               USD
2014-01-06       400               USD
2014-01-06       400               CAD

使用連接

import pandas as pd


print(pd.concat(
    [df['Buy'], df['sell']], axis=1
).stack().reset_index(1, drop=True).rename(index='buy/sell')
)

輸出:

0    100
0    100
1    200
1    200
2    300
2    300
3    400
3    400
# assuming that your data has date as index.
df.set_index('date', inplace=True)


# create a mapping to new column names
d={'Buy Currency': 'Buy/Sell Currency', 
   'Sell Currency' : 'Buy/Sell Currency',
   'Buy' : 'Buy/Sell',
   'Sell' :'Buy/Sell'
  }
df.columns=df.columns.map(d)



# stack first two columns over the next two columns
out=pd.concat([ df.iloc[:,:2],
            df.iloc[:,2:]
          ],
           ignore_index=True
          )
out
    Buy/Sell    Buy/Sell Currency
0   100     CAD
1   200     USD
2   300     CAD
3   400     USD
4   100     USD
5   200     CAD
6   300     USD
7   400     CAD

暫無
暫無

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

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