【问题标题】:Pandas: Concatenate multiple column values one below the other熊猫:连接多个列值一个在另一个之下
【发布时间】:2019-03-21 09:30:34
【问题描述】:

我有这个数据框:

    0                     1
0  Bin  Months Since Default
1    1                     0
2    2              0< x <=6
3    3             6< x <=12
4    4            12< x <=24
5    5                   24<

我想创建一个新列“文本”,它将 0 和 1 连接在另一个下方,这样生成的数据框如下所示:

    0                     1    texts
0  Bin  Months Since Default    Bin
1    1                     0     1
2    2              0< x <=6     2
3    3             6< x <=12     3
4    4            12< x <=24     4
5    5                   24<     5
6    NaN                NaN      Months Since Default
7    NaN                NaN      0< x <=6
8    NaN                NaN      6< x <=12
9    NaN                NaN      12< x <=24
10   NaN                NaN      24<

有可能吗?

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    DataFrame.meltconcat 一起使用:

    #by all columns
    s = df.melt(value_name='texts')['texts']
    #if need filter columns by list
    #s = df[[0,1]].melt(value_name='texts')['texts']
    df = pd.concat([df, s], axis=1)
    print (df)
          0                     1                 texts
    0   Bin  Months Since Default                   Bin
    1     1                     0                     1
    2     2              0< x <=6                     2
    3     3             6< x <=12                     3
    4     4            12< x <=24                     4
    5     5                   24<                     5
    6   NaN                   NaN  Months Since Default
    7   NaN                   NaN                     0
    8   NaN                   NaN              0< x <=6
    9   NaN                   NaN             6< x <=12
    10  NaN                   NaN            12< x <=24
    11  NaN                   NaN                   24<
    

    【讨论】:

      猜你喜欢
      • 2019-12-04
      • 2014-04-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 2023-03-10
      • 2022-11-16
      • 2013-10-14
      • 2022-10-12
      相关资源
      最近更新 更多