【问题标题】:How to assign a new descriptive column while concatenating data frames in python如何在python中连接数据框时分配新的描述性列
【发布时间】:2020-12-28 16:49:42
【问题描述】:

我有两个要在 python 中连接的数据框。但是,我想添加另一列 type 以区分列。

这是我的示例数据:

import pandas as pd
df = pd.DataFrame({'numbers': [1, 2, 3], 'colors': ['red', 'white', 'blue']}, 
                  columns=['numbers', 'colors'])

df1 = pd.DataFrame({'numbers': [7, 9, 9], 'colors': ['yellow', 'brown', 'blue']}, 
                  columns=['numbers', 'colors'])
pd.concat([df,df1])

这段代码会给我以下结果:

    numbers colors
0   1   red
1   2   white
2   3   blue
0   7   yellow
1   9   brown
2   9   blue

但我想得到如下:

  numbers colors  type
0   1   red       first
1   2   white     first
2   3   blue      first
0   7   yellow    second
1   9   brown     second
2   9   blue      second

类型列将帮助我区分两个数据框的值。

谁能帮我解决这个问题?

【问题讨论】:

    标签: python pandas dataframe merge concat


    【解决方案1】:

    对新列使用DataFrame.assign

    df = pd.concat([df.assign(typ='first'),df1.assign(typ='second')])
    print (df)
       numbers  colors     typ
    0        1     red   first
    1        2   white   first
    2        3    blue   first
    0        7  yellow  second
    1        9   brown  second
    2        9    blue  second
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2020-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-23
      相关资源
      最近更新 更多