首页 > 解决方案 > 如何组合这两列?熊猫

问题描述

我有两列,一是买家 ID,一是卖家 ID。我试图简单地找出两者的组合出现最多。

def twoCptyFreq(df,col1,col2):
    cols=[col1,col2]
    df['TwoCptys']=df[cols].astype(str).apply('+'.join, axis=1)
    return (df)

newdf=twoCptyFreq(tradedf,'BuyerID','SellerID')

我得到了我想要的结果,但有时我得到 1234+7651 和 7651+1234,所以两个相同,但我需要将它们聚合在一起。我如何将其写入我的函数以允许买卖双方可以互换的情况?

标签: pythonpython-3.xpandascombinations

解决方案


您可以通过以下方式在 lambda 函数中对值进行排序sorted

df['TwoCptys']=df[cols].astype(str).apply(lambda x: '+'.join(sorted(x)), axis=1)

或在通过以下方式转换为二维数组的列中np.sort

df['TwoCptys']= (pd.DataFrame(np.sort(df[cols].values, axis=1))
                   .astype(str).apply('+'.join, axis=1))

推荐阅读