【问题标题】:Append a string item to lists in a Pandas Column将字符串项附加到 Pandas 列中的列表
【发布时间】:2020-06-02 16:58:58
【问题描述】:

对于熊猫数据框:

Name:        Tags:
'One'        ['tag1', 'tag3']
'Two'        []
'Three'      ['tag1']

如何将“tag2”附加到标签列表中?

我尝试了以下方法(addtag2 是另一个 df):

df['Tags'] = df['Tags'].astype(str) + ', ' + addtag2['Tags'].astype(str)

df['Tags'] = df['Tags'].add(addtag2['Tags'].astype(str))

但他们将字符串附加到列表之外,例如 ['tag1']、tag2 或 ['tag1']tag2

期望的输出是:

Name:        Tags:
'One'        ['tag1', 'tag3', 'tag2']
'Two'        ['tag2']
'Three'      ['tag1', 'tag2']

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这是apply 派上用场的一个例子:

    df['Tags'] = df['Tags'].apply(lambda x: x + ['tag2'])
    

    或者你可以做一个for循环:

    for x in df.Tags: x.append('tag2')
    

    输出:

        Name                Tags
    0    One  [tag1, tag3, tag2]
    1    Two              [tag2]
    2  Three        [tag1, tag2]
    

    【讨论】:

    • df['Tags'].apply(lambda x: x.append('tag2'))
    • @QuangHoang 它对我有用;你是什​​么意思? df['Tags'] = df['Tags'].apply(lambda x: x.append('tag2')) 不起作用,但如果您只是在等号后调用该位,它就可以工作(df 已就地修改)
    • @Tom 是的。我的道歉。
    【解决方案2】:

    或者您可以使用append

    df['Tags'] = df['Tags'].apply(lambda x: x.append('tag2') or x)
    

    输出:

        Name                Tags
    0    One  [tag1, tag3, tag2]
    1    Two              [tag2]
    2  three        [tag1, tag2]
    

    【讨论】:

      猜你喜欢
      • 2018-09-13
      • 2012-12-05
      • 2021-08-11
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-12
      • 2017-08-06
      • 1970-01-01
      相关资源
      最近更新 更多