您可以将两列添加在一起以获得您要查找的列表,然后使用df.drop()
with axis=1
删除ids_x
and ids_y
列。例子 -
df = pd.merge(df1, df2, on='date', sort=False)
df['ids'] = df['ids_x'] + df['ids_y']
df = df.drop(['ids_x','ids_y'],axis=1)
Demo -
In [65]: df
Out[65]:
date ids_x ids_y
0 2015-10-13 [978] [978, 12]
1 2015-10-14 [978, 121] [2, 1]
In [67]: df['ids'] = df['ids_x'] + df['ids_y']
In [68]: df
Out[68]:
date ids_x ids_y ids
0 2015-10-13 [978] [978, 12] [978, 978, 12]
1 2015-10-14 [978, 121] [2, 1] [978, 121, 2, 1]
In [70]: df = df.drop(['ids_x','ids_y'],axis=1)
In [71]: df
Out[71]:
date ids
0 2015-10-13 [978, 978, 12]
1 2015-10-14 [978, 121, 2, 1]
如果您还想删除重复值,并且您不关心顺序,那么你可以使用Series.apply
然后将列表转换为set
然后回到list
。例子 -
df['ids'] = df['ids'].apply(lambda x: list(set(x)))
Demo -
In [72]: df['ids'] = df['ids'].apply(lambda x: list(set(x)))
In [73]: df
Out[73]:
date ids
0 2015-10-13 [978, 12]
1 2015-10-14 [121, 978, 2, 1]
或者按照评论中的要求,如果您想这样做numpy.unique()
,您可以将其与Series.apply
还有——
import numpy as np
df['ids'] = df['ids'].apply(lambda x: np.unique(x))
Demo -
In [79]: df['ids'] = df['ids'].apply(lambda x: np.unique(x))
In [80]: df
Out[80]:
date ids
0 2015-10-13 [12, 978]
1 2015-10-14 [1, 2, 121, 978]