【问题标题】:Generate a list for row-column combinations in one dataframe, with data from a second dataframe containing more column-value combinations为一个数据框中的行列组合生成一个列表,其中第二个数据框中的数据包含更多列值组合
【发布时间】:2021-02-20 07:41:09
【问题描述】:

我需要为每个国家/地区生成不同年份的人口列表。我需要的信息包含在两个数据框中

  1. 第一个数据框 gni_per_capita 包含国家名称和 年。此数据框中的国家/地区具有不同的年份范围

  2. 第二个数据框 hihd 也有国家和日期的名称, 但国家名单更广泛,范围更广 每个国家/地区的日期范围。 第二个数据框包含每个国家每年的人口,第二个没有。

我需要为第一个数据框中的每个国家/地区每年生成一份人口列表。

我得到了以下提示:

1. first, get a unique list of countries from gni_per_capita. 
2. Loop through the list, and get the available years for that country. 
3. Then .loc index hihd to get the population rows where both the country
    and years are correct (hihd.Year.isin(?)). 
4. Append these to the list
    one by one.

到目前为止,我已经从第一个数据框创建了一个包含国家和年份的系列

group = gni_per_capita.groupby('Entity')

ync = group.apply(lambda x: x['Year'].unique())

但是,我正在努力将第二个数据框与创建的系列结合起来

mask = hihd.Year.isin(ync)

【问题讨论】:

标签: python pandas dataframe lambda isin


【解决方案1】:

你为什么不用merge

两个样本帧

gni_per_capita = pd.DataFrame(
    {'Entity': 2 * ['A'] + 3 * ['B'],
     'Year': list(range(2020, 2020 + 2)) + list(range(2020, 2020 + 3))}
)
hihd = pd.DataFrame(
    {'Entity': 4 * ['A'] + 4 * ['B'] + 4 * ['C'],
     'Year': 3 * list(range(2019, 2023)),
     'Population': list(range(10, 14)) + list(range(20, 24)) + list(range(30, 34))}
)
  Entity  Year
0      A  2020
1      A  2021
2      B  2020
3      B  2021
4      B  2022

   Entity  Year  Population
0       A  2019          10
1       A  2020          11
2       A  2021          12
3       A  2022          13
4       B  2019          20
5       B  2020          21
6       B  2021          22
7       B  2022          23
8       C  2019          30
9       C  2020          31
10      C  2021          32
11      C  2022          33

这个

gni_per_capita.merge(hihd, how='left', on=['Entity', 'Year'])

给你

  Entity  Year  Population
0      A  2020          11
1      A  2021          12
2      B  2020          21
3      B  2021          22
4      B  2022          23

这似乎是你想要的。还是我错过了什么?

如果你想要它作为list

result = (gni_per_capita.merge(hihd, how='left', on=['Entity', 'Year'])
          .to_numpy().tolist())
[['A', 2020, 11], ['A', 2021, 12], ['B', 2020, 21], ['B', 2021, 22], ['B', 2022, 23]]

【讨论】:

    猜你喜欢
    • 2021-08-09
    • 1970-01-01
    • 2018-02-17
    • 2021-01-11
    • 2021-04-11
    • 2020-01-01
    • 1970-01-01
    • 2017-04-14
    • 1970-01-01
    相关资源
    最近更新 更多