我有两列,一列是买方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,所以这两个是一样的,但我需要把它们聚合在一起。我如何将其写入我的函数中,以支持买方和卖方可能被交换的情况?
发布于 2019-05-23 17:23:46
您可以按sorted对lambda函数中的值进行排序
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))发布于 2019-05-23 17:45:01
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 occurenceshttps://stackoverflow.com/questions/56271979
复制相似问题