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

时间:2017-08-25 11:22:15

标签: python pandas dataframe lambda

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

以下是一个示例数据框:

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

这是数据框的样子:

index col1  col2 

0     1     2 

1     2     1 

2     3     4

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

key_column看起来像这样:

0   [1, 2]

1   [1, 2]

2   [3, 4]

然后我会使用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

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

2 个答案:

答案 0 :(得分:4)

选项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)

选项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)

答案 1 :(得分:2)

三个步骤:

seaborn