【问题标题】:How do I combine these two columns? Pandas如何组合这两列?熊猫
【发布时间】:2019-05-23 09:20:44
【问题描述】:

我有两列,一是买家 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,所以两个相同,但我需要将它们聚合在一起。如何将其写入我的函数以允许买卖双方可以互换的情况?

【问题讨论】:

    标签: python python-3.x pandas combinations


    【解决方案1】:

    您可以在 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))
    

    【讨论】:

      【解决方案2】:
      df=pd.DataFrame({'A':[1,1,1],'B':[2,3,2],'C':[9,9,9]})
      
      df['combination']=df['A'].astype(str) + '+' + df['B'].astype(str)
      
      df['combination'].value_counts()
      out[]:
      1+2    2
      1+3    1
      Name: combination, dtype: int64
      
      #This shows combination of df[A] ==1 and df[B] ==2 has more occurences
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-15
        • 1970-01-01
        • 2014-10-20
        • 2019-05-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多