繁体   English   中英

在python中连接数据框时如何分配新的描述性列

[英]How to assign a new descriptive column while concatenating data frames in python

我有两个要在 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

type column 将帮助我区分两个数据框的值。

任何人都可以帮我解决这个问题吗?

对新列使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM