kit*_*sin 7 python merge list unique pandas
我有一个pandas数据帧如下:
如何将所有列表(在'val'列中)组合成一个唯一的列表(set),例如[val1, val2, val33, val9, val6, val7]?
我可以使用以下代码解决这个问题.我想知道是否有更简单的方法从列中获取所有唯一值而不迭代数据帧行?
def_contributors=[]
for index, row in df.iterrows():
contri = ast.literal_eval(row['val'])
def_contributors.extend(contri)
def_contributors = list(set(def_contributors))
Run Code Online (Sandbox Code Playgroud)
jez*_*ael 15
导出Series到嵌套的另一个解决方案lists然后应用于set展平列表:
df = pd.DataFrame({'id':['a','b', 'c'], 'val':[['val1','val2'],
['val33','val9','val6'],
['val2','val6','val7']]})
print (df)
id val
0 a [val1, val2]
1 b [val33, val9, val6]
2 c [val2, val6, val7]
print (type(df.val.ix[0]))
<class 'list'>
print (df.val.tolist())
[['val1', 'val2'], ['val33', 'val9', 'val6'], ['val2', 'val6', 'val7']]
print (list(set([a for b in df.val.tolist() for a in b])))
['val7', 'val1', 'val6', 'val33', 'val2', 'val9']
Run Code Online (Sandbox Code Playgroud)
时间:
df = pd.concat([df]*1000).reset_index(drop=True)
In [307]: %timeit (df['val'].apply(pd.Series).stack().unique()).tolist()
1 loop, best of 3: 410 ms per loop
In [355]: %timeit (pd.Series(sum(df.val.tolist(),[])).unique().tolist())
10 loops, best of 3: 31.9 ms per loop
In [308]: %timeit np.unique(np.hstack(df.val)).tolist()
100 loops, best of 3: 10.7 ms per loop
In [309]: %timeit (list(set([a for b in df.val.tolist() for a in b])))
1000 loops, best of 3: 558 µs per loop
Run Code Online (Sandbox Code Playgroud)
如果类型不是,list但string使用str.strip和str.split:
df = pd.DataFrame({'id':['a','b', 'c'], 'val':["[val1,val2]",
"[val33,val9,val6]",
"[val2,val6,val7]"]})
print (df)
id val
0 a [val1,val2]
1 b [val33,val9,val6]
2 c [val2,val6,val7]
print (type(df.val.ix[0]))
<class 'str'>
print (df.val.str.strip('[]').str.split(','))
0 [val1, val2]
1 [val33, val9, val6]
2 [val2, val6, val7]
Name: val, dtype: object
print (list(set([a for b in df.val.str.strip('[]').str.split(',') for a in b])))
['val7', 'val1', 'val6', 'val33', 'val2', 'val9']
Run Code Online (Sandbox Code Playgroud)
将该列转换为DataFrame .apply(pd.Series).如果堆叠列,则可以unique在返回的Series上调用该方法.
df
Out[123]:
val
0 [v1, v2]
1 [v3, v2]
2 [v4, v3, v2]
Run Code Online (Sandbox Code Playgroud)
df['val'].apply(pd.Series).stack().unique()
Out[124]: array(['v1', 'v2', 'v3', 'v4'], dtype=object)
Run Code Online (Sandbox Code Playgroud)