用熊猫将一个字符串列组合到另一个

时间:2018-06-27 01:05:19

标签: python pandas

如果我具有以下数据框:

id     categories      products
01        fruit       Apple, Apricot
02        fruit       Apple, Banana, Clementine, Pear
03        fruit       Orange, Pineapple, Pear
04      vegetable     Carrot, Cabbage

我想创建一个新的df,我该怎么办?谢谢。

id          products
01     (fruit)Apple, Apricot
02     (fruit)Apple, Banana, Clementine, Pear
03     (fruit)Orange, Pineapple, Pear
04     (vegetable)Carrot, Cabbage

2 个答案:

答案 0 :(得分:4)

只是求和字符串

"(" + df.categories + ")" + df.products

答案 1 :(得分:0)

尝试

    df = df.set_index('id')
    df  =df.apply(lambda x: "(" + x['categories'] + ")" + x['products'],axis=1).to_frame('products')
    print df