如何在熊猫列中获取唯一的子字符串

时间:2019-04-12 08:09:00

标签: python python-3.x pandas dataframe

我有一个如下数据框:

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)

哪个可以给我正确的结果,但是有更有效的方法吗?

我的原始数据集有大约一百万行和数千个不定值。

2 个答案:

答案 0 :(得分:5)

您可以先使用join创建一个长字符串,然后使用split并将其转换为set,最后转换为list

a = list(set(', '.join(df['b']).split(', ')))
print (a)
['south', 'north', 'west', 'east']

或将set comprehensionsplit结合使用并展平:

a = list(set([y for x in df['b'] for y in x.split(', ')]))
print (a)
['south', 'north', 'west', 'east']

纯熊猫解决方案是使用Series.str.splitDataFrame.stackSeries.unique并转换为list

a = df.b.str.split(', ', expand=True).stack().unique().tolist()

答案 1 :(得分:0)

您必须分析代码以确定对于特定用例而言这是否更快,但是使用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())
相关问题