python - 如何组合这两列?熊猫
问题描述
我有两列,一是买家 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,所以两个相同,但我需要将它们聚合在一起。我如何将其写入我的函数以允许买卖双方可以互换的情况?
解决方案
您可以通过以下方式在 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))
推荐阅读
- naudio - 如何关闭或重置 ASIO 驱动程序
- flutter - 当数据具有相同类别时如何从波纹管列表中删除数据,因此gridview没有重复的类别名称
- javascript - 如何在 ExpressJS 中一起渲染和重定向
- c# - 有没有办法使用服务器不支持的密码套件进行连接?
- python - 将多行传递给python脚本中的程序
- react-native - 从嵌套在 Stack Navigator 中的 Tab Navigator 导航
- javascript - react redux 中间件无法访问 utils 中定义的变量
- javascript - 确定相邻重复数组元素的索引
- r - R ggplot 和 ggpubr,如何计算/显示 facet_wrap 图中的 p 值,不同图中的不同组?
- javascript - 如何同时和异步进行多个ajax调用