如果满足某些条件,则用另一个数据框的列中的值填充空数据框或数组 pandas

问题描述 投票:0回答:2

我需要创建一个空数据框,根据同一第二个数据框的两列中满足的某些条件来存储另一个数据框的列中的值。

我有一个数据框

test_mob_df = pd.DataFrame( {"geoid_o": [10002, 18039, 18039, 18182, 10006, 18111, 18005, 17001], "geoid_d": [10005, 18039, 18111, 18182, 18005, 17004, 18050, 15001], "pop_flows": [20,10,9,15,2,1,6,30]})
以及我感兴趣的 id 列表
state_county_fip = [18182, 18111, 18005, 18039, 18050, 18001]
。我现在需要创建一个新的 $nxn$ 数据框(或数组),其行和列名称已排序
state_county_fips
,只要值位于同一行列中,该数据框就将值存储在 $test_mob_df$ 的
pop_flows
列中
geoid_o
geoid_d
匹配或不匹配。本质上,生成的数据框应该如下所示:

18005 18039 18005 18050 18111 18182
18005 0 0 0 0 0 0
18039 0 10 0 0 9 0
18005 0 0 0 6 0 0
18050 0 0 0 0 0 0
18111 0 0 0 0 0 0
18182 0 0 0 0 0 15

也就是说,我需要创建一个从 geoid_o 到 geoid_d 的人口流的数据框(或矩阵),当我们没有从 geoid_o 到 geoid_d 的人口流时,我们将零分配给相应的单元格。例如,有 10 个人从 geoid_o 18005 移至 geoid_d 18050。

除了使用查询创建具有感兴趣的大地水准面的数据框(来自 test_mob_df)之外,我似乎不知道如何做到这一点:

data_counties_of_interest = test_mob_df.query("18001<=geoid_o<18200 and 18001<=geoid_d<18200")
。我将非常感谢您提供的任何帮助。

python pandas dataframe numpy indexing
2个回答
3
投票
(test_mob_df[['geoid_o', 'geoid_d']]
  .apply(pd.Categorical, categories = sorted(state_county_fip))
  .assign(p = test_mob_df['pop_flows'])
  .pivot_table('p', 'geoid_o', 'geoid_d', fill_value=0, dropna = False))

geoid_d  18001  18005  18039  18050  18111  18182
geoid_o                                          
18001        0      0      0      0      0      0
18005        0      0      0      6      0      0
18039        0      0     10      0      9      0
18050        0      0      0      0      0      0
18111        0      0      0      0      0      0
18182        0      0      0      0      0     15

2
投票

你可以这样做:

test_mob_df = pd.DataFrame(
    {
        "geoid_o": [10002, 18039, 18039, 18182, 10006, 18111, 18005, 17001],
        "geoid_d": [10005, 18039, 18111, 18182, 18005, 17004, 18050, 15001],
        "pop_flows": [20, 10, 9, 15, 2, 1, 6, 30],
    }
)

state_county_fip = [18182, 18111, 18005, 18039, 18050, 18001]

out = pd.crosstab(
    test_mob_df.loc[test_mob_df["geoid_o"].isin(state_county_fip), "geoid_o"],
    test_mob_df.loc[test_mob_df["geoid_d"].isin(state_county_fip), "geoid_d"],
    values=test_mob_df["pop_flows"],
    aggfunc="first",
)

out = (
    out.reindex(index=state_county_fip, columns=state_county_fip)
    .fillna(0)
    .sort_index(axis=1)
    .sort_index()
    .astype(int)
)

print(out)

打印:

geoid_d  18001  18005  18039  18050  18111  18182
geoid_o                                          
18001        0      0      0      0      0      0
18005        0      0      0      6      0      0
18039        0      0     10      0      9      0
18050        0      0      0      0      0      0
18111        0      0      0      0      0      0
18182        0      0      0      0      0     15
© www.soinside.com 2019 - 2024. All rights reserved.