在下面的数据框中,我想打印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
假设数据帧中的每个值都很重要,下面是我经常使用的“解包列表”技术:
让我们用
type
如果值是列表,则通过
isinstance
方法检查:您的解决方案应该通过强制转换为字符串和
regex=False
参数进行更改:另外,如果要将熊猫0.25+的所有唯一值包括在列表中:
相关问题 更多 >
编程相关推荐