【问题标题】:Concatenating multiple columns into one while copying values of other columns将多列连接为一列,同时复制其他列的值
【发布时间】:2019-07-27 16:15:51
【问题描述】:

我有以下数据框:

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

有人可以帮我吗?谢谢。

【问题讨论】:

  • 嗨!您能否向我们展示一些您迄今为止尝试过的代码?
  • 当然。我试图创建一个支点,但我没有得到想要的结果。
  • 确保选择正确的答案。
  • 完成@shaikmoed。

标签: python pandas merge concatenation


【解决方案1】:

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

【讨论】:

  • 非常感谢温.. 你是救世主。 :)
【解决方案2】:

使用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

【讨论】:

    猜你喜欢
    • 2018-09-01
    • 2012-06-29
    • 2021-02-23
    • 2020-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多