我有一個這樣的資料框(假設一列):
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 /
我正在努力以適當的方式完成這項作業。希望有人有好主意(轉換為小串列有意義嗎?)
uj5u.com熱心網友回復:
集合是一種類似于串列的資料型別,但它只包含唯一值。這意味著您可以將串列轉換為集合,然后再轉換回串列(如果您想要這些唯一值的串列)。
然后你會寫這樣的東西:
list(set(name_of_the_list))
uj5u.com熱心網友回復:
資料框內的嵌套串列不是一個好習慣,也許對于一些非常具體的問題。我強烈建議您閱讀如何堅持tidy 范式(我知道這是從 R 的角度來看的,但它可以很容易地轉錄成 python)。
盡管如此,使用Numpy函式作為unique并且sort可以為您的示例完成作業,假設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]
使用應用映射
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]
uj5u.com熱心網友回復:
假設您在列中有串列,請使用串列推導。
如果你想維持秩序:
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']]})
uj5u.com熱心網友回復:
杠桿設定。
如果已經是串列
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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/448477.html
上一篇:按R中的自定義函式排序
