如何从 pandas 中的多列创建排序值列表?

Ste*_*anK 0 python lambda dataframe pandas

我有一个包含 A 列和 B 列的数据框,它们在排序时可以具有相同的值对。我想对这些列进行重复数据删除,因为我不关心应用程序中的顺序。

这是一个示例数据框:

import pandas as pd
df = pd.DataFrame({'col1':[1, 2, 3], 'col2':[2, 1, 4]})
print(df)
Run Code Online (Sandbox Code Playgroud)

数据框如下所示:

index col1  col2 

0     1     2 

1     2     1 

2     3     4
Run Code Online (Sandbox Code Playgroud)

我想要实现的是创建一个新列,该列将包含每行的前两个值的排序列表,以便我能够根据该列对数据帧进行重复数据删除。

key_column 看起来像这样:

0   [1, 2]

1   [1, 2]

2   [3, 4]
Run Code Online (Sandbox Code Playgroud)

然后我会使用 df.drop_duplicates(col3)

我有一个想法,我应该使用 .apply 或 .map ,也许还有一些 lambda 函数,但到目前为止我尝试过的都不起作用:

df.apply(lambda row: sorted([row[0], row[1]]), axis=1) # this sorts the column values in place but doesn't create a new column with a list
sorted([df['col1'], df['col2']]) # returns error The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
df.map(sorted) # dataframe object has no attribute map
df[['col1', 'col2']].apply(lambda x:
    sorted([','.join(x.astype(int).astype(str))]), axis=1) # creates a list but is not sorted
Run Code Online (Sandbox Code Playgroud)

感谢您的帮助,我希望看到一个也有解释的解决方案 - 为什么它有效。

cs9*_*s95 5

选项1

使用df.apply并通过sorted

In [1234]: df['col3'] = df.apply(tuple, 1).apply(sorted).apply(tuple)

In [1235]: df.drop_duplicates('col3')
Out[1235]: 
   col1  col2    col3
0     1     2  (1, 2)
2     3     4  (3, 4)
Run Code Online (Sandbox Code Playgroud)

选项2

调用np.sort然后df.values将结果分配给新列。

In [1208]: df['col3'] = pd.Series([tuple(x) for x in np.sort(df.values, 1)]); df
Out[1208]: 
   col1  col2    col3
0     1     2  (1, 2)
1     2     1  (1, 2)
2     3     4  (3, 4)

In [1210]: df.drop_duplicates('col3')
Out[1210]: 
   col1  col2    col3
0     1     2  (1, 2)
2     3     4  (3, 4)
Run Code Online (Sandbox Code Playgroud)