我有以下数据框,我想在其中打印 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
df.colors.unique()
如果没有 [yellow , red]
会正常工作排。照原样,我不断收到 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
最佳答案
如果值是列表,请通过 isinstance
检查它方法:
#changed sample data
df = pd.DataFrame({'colors': ['green', 'green', 'purple', ['yellow' , 'red'], 'orange'],
'names': ['Terry', 'Nor', 'Franck', 'Pete', 'Agnes']})
df = df[~df.colors.map(lambda x : isinstance(x, list))]
print (df)
colors names
0 green Terry
1 green Nor
2 purple Franck
4 orange Agnes
您的解决方案应该更改为转换为字符串和
regex=False
范围:df = df[~df.colors.astype(str).str.contains('[', na=False, regex=False)]
print (df)
colors names
0 green Terry
1 green Nor
2 purple Franck
4 orange Agnes
此外,如果想要包含 Pandas 0.25+ 列表的所有唯一值:
s = df.colors.map(lambda x : x if isinstance(x, list) else [x]).explode().unique().tolist()
print (s)
['green', 'purple', 'yellow', 'red', 'orange']
关于python - 有列表时如何获取数据框列的唯一值-python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58434045/