使用
DataFrame.merge
具有
DataFrame
构造函数:
#if possible duplicates in ps remove them
ps = ps.drop_duplicates()
df = df.merge(pd.DataFrame({'idx': ps.index, 'a':ps.values}), on='a')
print (df)
a idx
0 [a, b, c] 0
1 [a, c, b] 1
2 [c, a, b] 4
老款pandas版本的解决方案-在之前将列表转换为元组
merge
:
df1 = ps.apply(tuple).reset_index().drop_duplicates(0)
print (df1)
index 0
0 0 (a, b, c)
1 1 (a, c, b)
2 2 (b, a, c)
3 3 (b, c, a)
4 4 (c, a, b)
5 5 (c, b, a)
df = (df.merge(df1, left_on=df['a'].apply(tuple),right_on=df1[0])
.drop(['key_0',0], axis=1))
print (df)
a index
0 [a, b, c] 0
1 [a, c, b] 1
2 [c, a, b] 4