【问题标题】:Merge Dataframes with Unique Values but keeping a tally合并具有唯一值但保持计数的数据框
【发布时间】:2021-01-30 00:21:10
【问题描述】:

我将用一个假设的示例问题来解释我的需求。 比如说,我们有四个数据框,每个人一个。带有位置和旅行日期的列。

例如:

#DataFrame1
   Location     Date
0  A            d1
1  B            d2
2  B            d3
3  A            d4

#DataFrame2
   Location     Date
0  B            d1
1  C            d2
2  D            d3
3  B            d3
4  C            d4

现在,我需要将所有这四个数据框合并为一个。第 1 列是四个数据框中所有位置的唯一列表,每个人的单独列是根据他们的旅行对位置进行“是”或“否”。

#Output Dataframe
    Location    Person1    Person2
0   A           Yes        No
1   B           Yes        Yes
2   C           No         Yes
3   D           No         Yes

我该如何处理?

到目前为止,我都是这样想的。

  • 我可以在单个数据框(因此每个人去过的地方)下获得一组唯一值:p1_places = df1['Location'].unique()
  • 我可以通过创建一个集合来获得所有人旅行过的所有地方的组合列表(此处为 A、B、C、D)。 for place in p1_places: set_locations.add(place)

但我不知道如何将此集合与 person1 和 person2 匹配,然后创建一个带有结果的列。

【问题讨论】:

    标签: python pandas dataframe merge


    【解决方案1】:

    你在正确的轨道上。根据您的直觉,以下代码 sn-p 可以解决问题。

    识别人 1 和 2 访问的唯一位置后,合并列表并仅保留唯一元素:

    p1_places = list(df1['Location'].unique())
    p2_places = list(df2['Location'].unique())
    all_places = list(set(p1_places + p2_places))
    
    

    确定 person1 和 person2 去过的地方:

    p1_visited = []
    p2_visited = []
    
    for i in all_places:
        if i in p1_places: 
            p1_visited.append('Yes')
        else:
            p1_visited.append('No')
        if i in p2_places: 
            p2_visited.append('Yes')
        else:
            p2_visited.append('No')
    
    

    创建一个新的数据框:

    new_df = pd.DataFrame()
    
    new_df['Location'] = all_places
    new_df['Person 1'] = p1_visited
    new_df['Person 2'] = p2_visited
    

    new_df.head() 的输出将是:

        Location    Person 1    Person 2
    0      B          Yes         Yes
    1      C          No          Yes
    2      D          No          Yes
    3      A          Yes         No
    

    【讨论】:

    • 那很整洁。我被困在如何组合两组或两个数据框列或两个数组,但如果没有“+”操作员就无法做到。只需创建一个列表,这是一个很好的解决方案。谢谢。
    • 很高兴知道这有帮助!如果您能接受答案并让其他人知道您是如何解决问题的,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多