首页 > 解决方案 > 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'])

但这仅在我将列转换为字符串时才有效。如何做到这一点?

标签: pythonpandasdata-preprocessing

解决方案


首先让我们编写一个函数来删除'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]

推荐阅读