【问题标题】:Data Loops Python数据循环 Python
【发布时间】:2020-12-21 22:04:46
【问题描述】:

我有两个数据框:

df_id:

name         id
region 01    850
region 01    15062
region 02    851

df_combination:

Origin      destination    total
region 01   region 01      1954
region 01   region 02      39

我必须执行区域 01 和区域 02 之间的所有可能组合,并将总数除以组合总数。

类似这样的输出:

Origin_id       Destination_id       Total_division
850             850                  488.5
850             15062                488.5
15062           850                  488.5
15062           15062                488.5
850             851                  19.5
15062           851                  19.5

我有超过 300 个区域,所以我想知道是否可以通过 python 代码(也许是循环)来实现。

【问题讨论】:

    标签: python pandas dataframe loops data-structures


    【解决方案1】:

    此代码将准确高效地为您提供所需的内容;-)
    它为 df_combination 中的每一行构建一个数据框,并在最后将它们全部连接起来。

    import pandas as pd
    from itertools import product
    
    dict_region_to_ids = {reg: list(ids) for reg, ids in df_id.groupby("name")["id"]}
    dfs = []
    for r1, r2, total in df_combination.itertuples(index=False):
        df = pd.DataFrame(product(dict_region_to_ids[r1], dict_region_to_ids[r2]), 
                          columns=["Origin_id", "Destination_id"])
        df["Total_division"] = total / len(df)
        dfs.append(df)
    df = pd.concat(dfs)
    df
    

    【讨论】:

    • 天啊!!你救了我的命!!!非常感谢你!!!!!!!!!!
    【解决方案2】:

    这是另一个建议:

    df = df_combination.merge(df_id, left_on='Origin', right_on='name')
    df = df.merge(df_id, left_on='destination', right_on='name')
    for _, group in df.groupby(['Origin', 'destination']):
        df.loc[group.index, 'total'] /= group.shape[0]
    df = df[['id_x', 'id_y', 'total']].rename(
                columns={'id_x': 'Origin_id', 'id_y': 'Destination_id',
                         'total': 'Total_division'}
            )
    

    结果(print(df)):

       Origin_id  Destination_id  Total_division
    0        850             850           488.5
    1        850           15062           488.5
    2      15062             850           488.5
    3      15062           15062           488.5
    4        850             851            19.5
    5      15062             851            19.5
    

    【讨论】:

      猜你喜欢
      • 2019-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 2013-08-29
      • 2019-09-21
      相关资源
      最近更新 更多