【发布时间】:2019-12-22 00:38:38
【问题描述】:
只是期待一种解决方案,从具有列表值的列中删除空值,在某种意义上,我们已经预先替换了一些字符串,它是列表的字符串表示列。
在df.color 中,我们只是将*._Blue 替换为空字符串:
示例数据框:
df = pd.DataFrame({ 'Bird': ["parrot", "Eagle", "Seagull"], 'color': [ "['Light_Blue','Green','Dark_Blue']", "['Sky_Blue','Black','White', 'Yellow','Gray']", "['White','Jet_Blue','Pink', 'Tan','Brown', 'Purple']"] })
>>> df
Bird color
0 parrot ['Light_Blue','Green','Dark_Blue']
1 Eagle ['Sky_Blue','Black','White', 'Yellow','Gray']
2 Seagull ['White','Jet_Blue','Pink', 'Tan','Brown', 'Pu...
上述DF的结果:
>>> df['color'].str.replace(r'\w+_Blue\b', '')
0 ['','Green','']
1 ['','Black','White', 'Yellow','Gray']
2 ['White','','Pink', 'Tan','Brown', 'Purple']
Name: color, dtype: object
通常在python中很容易做到如下......
>>> lst = ['','Green','']
>>> [x for x in lst if x]
['Green']
恐怕可以做到以下几点。
df.color.mask(df == ' ')
【问题讨论】:
-
对于包含列表或其他难以粘贴对象的数据框,应使用
to_dict创建minimal reproducible example,以便于重新创建。 -
@user3483203,很抱歉..刚刚更新了帖子上的信息,希望对您有所帮助。
-
所以你的列不是列表列,而是列表的字符串表示列?
-
这是真的@user3483203 在帖子中添加了相同的内容。
标签: regex python-3.x pandas numpy