python - Python Pandas:如果字符串值列表== [无],则从数据框中删除行
问题描述
我的数据框中有一列包含值列表。
Tags
[marvel, comics, comic, books, nerdy]
[new, snapchat, version, snap, inc]
[none]
[new, york, times, ny, times, nyt, times]
[today, show, today, show, today]
[none]
[mark, wahlberg, marky, mark]
我不知道如何从数据框中删除此 [none] 列表。我试过了,
us_videos = us_videos.drop(us_videos.index[us_videos.tags == 'none'])
但这仅在我将列转换为字符串时才有效。如何做到这一点?
解决方案
首先让我们编写一个函数来删除'none'
列表中的内容:
print(df)
tags
0 [marvel, comics, comic, books, nerdy]
1 [new, snapchat, version, snap, inc]
2 [none]
3 [new, york, times, ny, times, nyt, times]
4 [today, show, today, show, today, none]
def delete_none(element):
new = []
for val in element:
if val != 'none':
new.append(val)
if len(new) == 0:
return np.nan
else:
return new
tags
现在我们在列上应用这个函数:
df.tags.apply(delete_none)
输出:
0 [marvel, comics, comic, books, nerdy]
1 [new, snapchat, version, snap, inc]
2 NaN
3 [new, york, times, ny, times, nyt, times]
4 [today, show, today, show, today]
推荐阅读
- android - fontFeatureSettings=smcp 在 Android 中不起作用
- angular - 角性能 - OnPush 增加周期数
- javascript - 检查一个元素是否在 2 个数组之间是通用的,然后从中分配值
- java - 在 Java Springboot 中将 CSV 转换为 JSON 数组
- python - 为什么此代码不适用于所有情况?
- php - wp_redirect 导致“无法修改标头信息”
- scala - 在使用 Apache POI Scala 写入值后,使用日期打开 excel 单元格时出现问题
- mysql - 使用多个表和限制选项更新查询
- javascript - 无法从 selenium webdriver 的 Kendo 下拉菜单中选择一个选项
- compiler-errors - F# Implicit ModuleSuffix not working when using fully qualified name