首页 > 解决方案 > 如何根据另一列python将值附加到一行中?

问题描述

我有一个看起来像这样的数据框:

        body              label
   the sky is blue        [noun]
   the apple is red.      [noun]
   Let's take a walk      [verb]

我想根据正文列中是否有颜色将项目添加到标签列表中。

期望的输出:

            body              label
       the sky is blue        [noun, color]
       the apple is red.      [noun, color]
       Let's take a walk      [verb]

我努力了:

data.loc[data.body.str.contains("red|blue"), 'label'] = data.label.str.append('color') 

标签: pythonpandas

解决方案


一种选择是apply在系列上使用,然后直接附加到列表:

data.loc[data.body.str.contains('red|blue'), 'label'].apply(lambda lst: lst.append('color'))

data
                body          label
0    the sky is blue  [noun, color]
1  the apple is red.  [noun, color]
2  Let's take a walk         [verb]

推荐阅读