将多列串联为一列,同时复制其他列的值

2024-05-18 10:51:53 发布

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

我有以下数据框:

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

有人能帮我吗??非常感谢。你知道吗


Tags: 数据datenanfasecuritieschinastanleydv
2条回答

dropna一起使用melt

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

使用^{}

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

相关问题 更多 >