如果顺序不重要,
set 就可以胜任:
import pandas as pd
data = [['a1', ['b1', 'b2'], ['c1', 'b1'], 'd1'],
['a2', ['b1', 'b1'], ['b3'], 'd2'],
['a3', ['b2'], ['b2', 'b2'], 'd3']]
df = pd.DataFrame(data=data, columns=['A', 'B', 'C', 'D'])
def uniques(xs):
return list(set(xi for x in xs for xi in x))
df['E'] = df[['B', 'C']].apply(uniques, axis=1)
print(df)
输出
A B C D E
0 a1 [b1, b2] [c1, b1] d1 [b1, b2, c1]
1 a2 [b1, b1] [b3] d2 [b1, b3]
2 a3 [b2] [b2, b2] d3 [b2]
如果顺序很重要,使用
OrderedDict:
import pandas as pd
from collections import OrderedDict
data = [['a1', ['b1', 'b2'], ['c1', 'b1'], 'd1'],
['a2', ['b1', 'b1'], ['b3'], 'd2'],
['a3', ['b2'], ['b2', 'b2'], 'd3']]
df = pd.DataFrame(data=data, columns=['A', 'B', 'C', 'D'])
def uniques(xs):
return list(OrderedDict().fromkeys(xi for x in xs for xi in x))
df['E'] = df[['B', 'C']].apply(uniques, axis=1)
输出
A B C D E
0 a1 [b1, b2] [c1, b1] d1 [b1, b2, c1]
1 a2 [b1, b1] [b3] d2 [b1, b3]
2 a3 [b2] [b2, b2] d3 [b2]
set
。 - Paul H