python - 将字符串项附加到 Pandas 列中的列表
问题描述
对于熊猫数据框:
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']
解决方案
这是一个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]
推荐阅读
- c# - 如何在 Blazor 应用程序中从 Http.PutAsJsonAsync 传递多个字符串值
- c++ - Eclipse IDE 未显示正确的输出
- android - GNU ld 消息:“添加符号时出错:文件格式错误的汇编语言”
- flutter - Dart如何以字节为单位调整图像的高度和宽度
- javascript - SetState 无法正常工作 React Native
- django - 尽管使用本地时间,Django 仍以 UTC 保存时间数据
- python - 修剪 sklearn 决策树以确保单调性
- android - Android Studio 中的上升和下降线动画
- swift - @Published 没有更新,状态问题?- 斯威夫特用户界面
- nuxt.js - NuxtJS + TailwindCSS 与 JIT + Vite