在复制其他列的值时将多个列连接成一列

问题描述 投票:6回答:2

我有以下数据框:

Date          DV        FA1              FA2           FA3           FA4
22/02/2019   200      Lazard             NaN           NaN           NaN 
2/02/2019    50      Deutsche           Ondra           NaN          NaN         
22/02/2019  120   China Securities      Ballas         Daiwa     Morgan Stanley

我需要将所有FA列连接成一列,同时还要复制Date和DV列。最终结果如下:

Date            DV        FA 
22/02/2019     200      Lazard             
2/02/2019       50      Deutsche           
2/02/2019       50      Ondra           
22/02/2019     120     China Securities
22/02/2019     120      Ballas           
22/02/2019     120      Daiwa     
22/02/2019     120     Morgan Stanley

谁有人可以帮我这个?谢谢。

python pandas merge concatenation
2个回答
3
投票

使用stack

df = (df.set_index(['Date','DV']).stack()
        .reset_index(level=[0,1], name='FA')
        .reset_index(drop=True))

print(df)
         Date   DV                FA
0  22/02/2019  200            Lazard
1   2/02/2019   50          Deutsche
2   2/02/2019   50             Ondra
3  22/02/2019  120  China Securities
4  22/02/2019  120            Ballas
5  22/02/2019  120             Daiwa
6  22/02/2019  120    Morgan Stanley

5
投票

使用meltdropna

yourdf=df.melt(['Date','DV']).dropna()
yourdf
          Date   DV variable            value
0   22/02/2019  200      FA1           Lazard
1    2/02/2019   50      FA1         Deutsche
2   22/02/2019  120      FA1  ChinaSecurities
4    2/02/2019   50      FA2            Ondra
5   22/02/2019  120      FA2           Ballas
8   22/02/2019  120      FA3            Daiwa
11  22/02/2019  120      FA4    MorganStanley
© www.soinside.com 2019 - 2024. All rights reserved.