我知道
df.name.unique()
将在一列'name'
中提供唯一值。
例如:
name report year
Coch Jason 2012
Pima Molly 2012
Santa Tina 2013
Mari Jake 2014
Yuma Amy 2014
array(['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], dtype=object)
但是,我们说我有~1000列,我想看到所有列'独特的价值观。
我该怎么做?
答案 0 :(得分:3)
您可以使用set
list(map(set,df.values.T))
Out[978]:
[{'Coch', 'Mari', 'Pima', 'Santa', 'Yuma'},
{'Amy', 'Jake', 'Jason', 'Molly', 'Tina'},
{2012, 2013, 2014}]
投入系列之后
pd.Series(list(map(set,df.values.T)),index=df.columns)
Out[980]:
name {Santa, Pima, Yuma, Coch, Mari}
report {Jason, Amy, Jake, Tina, Molly}
year {2012, 2013, 2014}
dtype: object
答案 1 :(得分:2)
如果您希望将结果列入清单,可以执行此类操作
[df[col_name].unique() for col_name in df.columns]
出:
[array(['Coch', 'Pima', 'Santa', 'Mari', 'Yuma'], dtype=object),
array(['Jason', 'Molly', 'Tina', 'Jake', 'Amy'], dtype=object),
array([2012, 2013, 2014])]
这将创建一个2D数组列表,其中每一行都是每列中唯一的值数组。
如果您想要列表的2D列表,可以将上面的内容修改为
[df[i].unique().tolist() for i in df.columns]
出:
[['Coch', 'Pima', 'Santa', 'Mari', 'Yuma'],
['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
[2012, 2013, 2014]]
答案 2 :(得分:1)
使用unique
字典理解:
pd.Series({c: df[c].unique() for c in df})
结果输出:
name [Coch, Pima, Santa, Mari, Yuma]
report [Jason, Molly, Tina, Jake, Amy]
year [2012, 2013, 2014]
答案 3 :(得分:0)
我做了以下事情。这样会将数据帧中所有列的所有唯一值归为一组。
unique_values = set()
for col in df:
unique_values.update(df[col])
答案 4 :(得分:0)
如果您只有数值,您可以转换为 numpy 数组并使用 numpy.unique()
:
假设您有一个只有数值的 Pandas Dataframe df,
import numpy as np
uniqueVals = np.unique(np.array(df))
如果你想要一个值列表
uniqueValsList = list(np.unique(np.array(df)))
(它不适用于这个问题,但可能会帮助其他人,就像我一样,只提供数字数据)