【问题标题】:How do I return the rows of DataFrame where every Country in each Continent has a Population of less of than 100?如何返回 DataFrame 的行,其中每个大陆的每个国家/地区的人口都少于 100?
【发布时间】:2022-11-21 11:07:16
【问题描述】:
df = pd.DataFrame({
    "Continent": list("AAABBBCCD"), 
    "Country": list("FGHIJKLMN"), 
    "Population": [90, 140, 50, 80, 80, 70, 50, 125, 50]})

如前所述,我想返回所有行,其中每个大陆的所有国家都小于 100。

  Continent Country  Population
0         A       F          90
1         A       G         140
2         A       H          50
3         B       I          80
4         B       J          80
5         B       K          70
6         C       L          50
7         C       M         125
8         D       N          50

A 大陆的每一行都被删除,因为 G 国的人口大于 100。C 大陆的每一行都因为 M 国而被删除。我希望返回的 DataFrame 如下所示:

  Continent Country  Population
3         B       I          80
4         B       J          80
5         B       K          70
8         D       N          50

我试过 df[df["Population"] <= 100] 但无法确定如何针对大陆进行调整。

【问题讨论】:

    标签: python pandas dataframe pandas-loc


    【解决方案1】:

    这是一种方法

    # groupby on continent
    # using makes the row True/False, whether max for the group is below 100
    out=df[df.groupby(['Continent'])['Population'].transform(lambda x: x.max()<100)]
    out
    
    
    Continent   Country     Population
    3   B   I   80
    4   B   J   80
    5   B   K   70
    8   D   N   50
    

    【讨论】:

      猜你喜欢
      • 2019-06-24
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-23
      • 2021-07-14
      • 2023-03-05
      • 1970-01-01
      相关资源
      最近更新 更多