在Pandas python中从列表中获取唯一值作为值

时间:2017-12-06 16:23:24

标签: python pandas dataframe

我有一个包含更多行和列的数据框,但有一个示例在这里:

id    values 
1   [v1, v2, v1]

如何从pandas列中的列表中获取唯一值? 第二列v1,v2中的所需输出 我尝试过df ['values']。unique()但显然它不起作用。

3 个答案:

答案 0 :(得分:2)

一个简单的解决方案是agg pd.unique,即

df = pd.DataFrame({'x' : [['v','w','x','v','x']]})

df['x'].agg(pd.unique) # Also np.unique

0    [v, w, x]
Name: x, dtype: object

df['x'].agg(set).agg(list)

0    [v, w, x]
Name: x, dtype: object

答案 1 :(得分:2)

再次

df['new']=list(map(set,df['values'].values))

时间

%timeit df['values'].agg(np.unique)
The slowest run took 6.78 times longer than the fastest. This could mean that an intermediate result is being cached.
100 loops, best of 3: 6.99 ms per loop
%timeit list(map(set,df['values'].values))
The slowest run took 55.36 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 228 µs per loop
%timeit df['values'].apply(lambda x: list(set(x)))
1000 loops, best of 3: 743 µs per loop

答案 2 :(得分:1)

尝试

df['values'] = df['values'].apply(lambda x: list(set(x)))


    id  values
0   1   [v2, v1]

注意:值是pandas属性,因此最好避免将其用作列名。

时间比较:

df= pd.DataFrame({'id':[1]*1000,    'values' :[['v1', 'v2', 'v1']]*1000})
%timeit df['values'].agg(np.unique)

34.7 ms ± 2.01 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)


%timeit df['values'].apply(lambda x: list(set(x)))

1.98 ms ± 259 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)