我有一个数据框如下:
df = pd.DataFrame({'a':[1,2,3,4],
'b':["west, east", "east, north","south, west","east, south"]})
a b
0 1 west, east
1 2 east, north
2 3 south, west
3 4 east, south
我想从列b
获得如下所示的独特字符串。
预期产出:
["east", "west", "north", "south"] # order doesn't matter here
我的努力
op = []
for _, value in df['b'].items():
op.extend(value)
op = set(op)
哪个给我正确的结果,但有更有效的方法吗?
我的原始数据集有大约一百万行和1000个唯一值。
您可以通过join
创建长字符串,然后split
并转换为set
,最后到list
:
a = list(set(', '.join(df['b']).split(', ')))
print (a)
['south', 'north', 'west', 'east']
或者使用set comprehension
和split
并展平:
a = list(set([y for x in df['b'] for y in x.split(', ')]))
print (a)
['south', 'north', 'west', 'east']
纯大熊猫解决方案是使用Series.str.split
,DataFrame.stack
,Series.unique
并转换为list
:
a = df.b.str.split(', ', expand=True).stack().unique().tolist()
您必须对代码进行概要分析以确定这对于您的特定用例是否更快,但使用pandas内置向量化方法可能会对较大的数据集显示一些好处。
尝试使用Series.str.split()和Series.unique()的组合。
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.str.split.html https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.unique.html
# Split column of lists into strings
df_split = df['b'].str.rsplit(',', n=-1, expand=True)
# For each column, get unique values and append to set
uniques = set()
for col in df_split:
uniques.update(df_split[col].unique())