如何删除列中字符串的重复部分并对值进行排序



我有一个这样的数据帧(假设一列(:

column
[A,C,B,A]
[HELLO,HELLO,ha]
[test/1, test/1, test2]

以上列的类型为:dtype('O'(

我想在这里删除重复项,结果是:

column
[A,C,B]                  # - A
[HELLO, ha]               # removing 1 hello
[test/1, test2]  # removing 1 test/1 

然后,我想对数据进行排序

column
[A,B,C]                  
[ha, HELLO]             
[test2, test/1]  # assuming that number comes before / 

我正在努力以正确的方式完成这项工作。希望有人有好的想法(转换为小列表有意义吗?(

集合是一种数据类型,它类似于列表,但只包括唯一的值。这意味着您可以将列表转换为集合,然后再转换回列表(如果您想要这些唯一值的列表(。

然后你会写这样的东西:

list(set(name_of_the_list))

数据帧中的嵌套列表不是一个好习惯,可能是针对一些真正特定的问题。我强烈鼓励你阅读如何坚持整洁的范式(我知道这是从R的角度来看的,但它可以很容易地转录到python中(。

尽管如此,使用Numpy函数作为uniquesort可以完成您的示例,假设df是您的数据帧:

在数据帧上使用for循环

df = pd.DataFrame({"col" : 
[["A","C","B","A"],
["HELLO","HELLO","ha"],
["test/1", "test/1", "test2"]]})

for n, value in df.iterrows():
df.loc[n, "col"] = np.sort(np.unique(value.loc["col"]))
df
Out[77]: 
col
0        [A, B, C]
1      [HELLO, ha]
2  [test/1, test2]

使用applymap

df2 = pd.DataFrame({"col" : 
[["A","C","B","A"],
["HELLO","HELLO","ha"],
["test/1", "test/1", "test2"]]})

df2 = df2.applymap(lambda x : np.sort(np.unique(x)))
df2
Out[75]: 
col
0        [A, B, C]
1      [HELLO, ha]
2  [test/1, test2]

假设列中有列表,请使用列表理解。

如果你想维持秩序:

df['column_keep_order'] = [list(dict.fromkeys(x)) for x in df['column']]

如果您想对项目进行排序:

df['column_sorted'] = [sorted(set(x)) for x in df['column']]

输出:

column column_keep_order    column_sorted
0             [A, C, B, A]         [A, C, B]        [A, B, C]
1       [HELLO, HELLO, ha]       [HELLO, ha]      [HELLO, ha]
2  [test/1, test/1, test2]   [test/1, test2]  [test/1, test2]

可再现输入:

df = pd.DataFrame({'column': [['A','C','B','A'],
['HELLO','HELLO','ha'],
['test/1', 'test/1', 'test2']]})

杠杆设置。

如果已经列出

df['column2']=[list(set(x)) for x in df.column.to_list()]

column          column2
0             [A, C, B, A]        [A, C, B]
1       [HELLO, HELLO, ha]      [HELLO, ha]
2  [test/1, test/1, test2]  [test2, test/1]

否则

df['column2']=df['column'].str.replace(']|[','',regex=True).str.split(',').map(set).map(list)

df['column2']=df['column'].str.replace(']|[','',regex=True).apply(lambda x:list(set(x.split(','))))


column          column2
0             [A, C, B, A]        [A, C, B]
1       [HELLO, HELLO, ha]      [HELLO, ha]
2  [test/1, test/1, test2]  [test2, test/1]

最新更新