熊猫数据框-数据重复但重复数据不位于同一列中

时间:2020-07-12 15:54:57

标签: python pandas dataframe

我有一个df,其中聚集了重复的行,但格式如下:

timestamp   animal_1  animal_2  
2020-06-28  14:28:57  dog fox    
2020-06-28  14:28:57  fox dog   
2020-06-29  18:28:57  dog fox   
2020-06-29  18:28:57  fox dog   
2020-06-30  17:35:57  dog fox   
2020-06-30  17:35:57  fox dog  

我只想保留具有唯一时间戳的行,然后是两种动物的单一组合。从上面的df中,我只想返回以下内容:

timestamp   animal_1  animal_2   
2020-06-28  14:28:57  dog fox    
2020-06-29  18:28:57  fox dog  
2020-06-30  17:35:57  dog fox  

重要的是,我返回了这两只动物互动的次数。

我曾经尝试过使用熊猫进行多种排序和分组选项,但是没有运气。

1 个答案:

答案 0 :(得分:1)

首先,我们需要对列动物drop_duplicates

进行排序
df[['animal_1', 'animal_2']]=np.sort(df[['animal_1', 'animal_2']].values, axis=1)
df=df.drop_duplicates()