Python:如何在两个数据帧之间合并和划分?

标签 python pandas dataframe

我有两个数据框df1df2df1 包含共享相同人口的两个地点之间的信息。

df1
     PlaceA  Population PlaceB
0     3         10         2
1     4         10         2
2     7         17         0
3     9         13         1

df2包含到达PlaceB的行进距离

df2
     PlaceB  distance
0      0       130
1      1       145
2      2       165

我想要一个在 PlaceB 上合并 df1df2 的数据框,并返回人口除以共享地点的数量相同的人口。例如,地点 2、3、4 拥有相同的人口,我们除以 3。

df3   
      Place     Population   Distance
0       0          17/2        130
1       1          13/2        145 
2       2          10/3        165
3       3          10/3        165
4       4          10/3        165
5       7          17/2        130
6       9          12/2        145

最佳答案

你可以尝试:

  1. PlaceB 上的两个数据框与 outer 合并,以确保考虑所有 PlaceB 值。 merge函数完成这项工作。
  2. 使用groupbyplaceB分组.
  3. 对于每个组:

    3.1。使用 meltPlaceAPlaceB 列转换为一列(称为 Place) .

    3.2。使用 drop_duplicates 删除重复项

    3.3。将 Population 列转换为所需的输出。在这里,我将其转换为字符串以匹配所需的输出。

可选(以匹配所需的输出):

  • 使用 sort_values地点对值进行排序.

  • 使用 drop 删除变量列

  • 使用 reset_index 重置并删除当前索引.

  • 代码如下:

    # Import module
    import pandas as pd
    
    # The input data
    df1 = pd.DataFrame({"PlaceA": [3, 4, 7, 9],
                        "Population": [10, 10, 17, 13],
                        "PlaceB": [2, 2, 0, 1]})
    df2 = pd.DataFrame({"PlaceB": [0, 1, 2], "distance": [130, 145, 165]})
    
    # Function to apply to each `PlaceB` group
    def melt_and_pop_up(x):
        x = x.melt(id_vars=['Population', 'distance'], value_name='Place') \
             .drop_duplicates()
        x.Population = "{}/{}".format(x.Population.values[0], len(x))
        # Get decimal values
        # x.Population = x.Population.values[0] / len(x)
        return x
    
    
    df = df1.merge(df2, on="PlaceB", how='outer')  \
            .groupby('PlaceB') \
            .apply(melt_and_pop_up) \
            .sort_values('Place') \
            .drop(columns=['variable'])  \
            .reset_index(drop=True) \
            [["Place", "Population", "distance"]]
    print(df)
    #    Place Population  distance
    # 0      0       17/2       130
    # 1      1       13/2       145
    # 2      2       10/3       165
    # 3      3       10/3       165
    # 4      4       10/3       165
    # 5      7       17/2       130
    # 6      9       13/2       145
    

    关于Python:如何在两个数据帧之间合并和划分?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57707067/

    相关文章:

    python - 如何在 Pygame 中翻转图像,在我的代码中遇到问题?

    python - 克隆和深复制之间的区别?

    python - 具有缺失值的列子集的逐行平均值

    python - 在不存在预先指定的条件的情况下插入 Pandas 数据框

    python - 数据框列值与列表的比较

    python - 在google colaboratory中使用opencv的文件路径加载文件

    python - 将字典的字典存储在 MySQL 数据库中

    python - Pandas 数据帧 : add column that counts like-events in past

    R 删除只有 NA 的组

    python - 优雅而高效地替换 pandas 列中的多个术语