【发布时间】:2019-10-17 13:38:13
【问题描述】:
我有以下数据框,我想在其中打印 color 列的唯一值。
df = pd.DataFrame({'colors': ['green', 'green', 'purple', ['yellow , red'], 'orange'], 'names': ['Terry', 'Nor', 'Franck', 'Pete', 'Agnes']})
Output:
colors names
0 green Terry
1 green Nor
2 purple Franck
3 [yellow , red] Pete
4 orange Agnes
如果没有[yellow , red] 行,df.colors.unique() 可以正常工作。事实上,我不断收到TypeError: unhashable type: 'list' 错误,这是可以理解的。
有没有办法在不考虑这一行的情况下仍然获得唯一值?
我尝试了以下方法,但没有成功:
df = df[~df.colors.str.contains(',', na=False)] # Nothing happens
df = df[~df.colors.str.contains('[', na=False)] # Output: error: unterminated character set at position 0
df = df[~df.colors.str.contains(']', na=False)] # Nothing happens
【问题讨论】:
-
理想情况下这应该可以工作,
df.loc[~df.colors.str.contains('[', na=False, regex=False), 'colors'].unique() -
以上代码返回['green', 'purple', 'orange']
-
@I.M.如果它们是唯一的或者你想忽略它们,你真的想要列表中的值吗?
-
由于某些原因,我也得到了
error: unterminated character set at position 0@MahendraSingh -
@vb_rises 我可以忽略它们,但理想的情况是即使它们是列表格式,也要拥有列的唯一值。