【问题标题】:How to iterate over columns and check condition by group如何遍历列并按组检查条件
【发布时间】:2022-01-14 17:03:27
【问题描述】:

我有一段时间(2001-2003 年)内许多国家的数据。它看起来像这样:

index year country inflation GDP
1 2001 AFG nan 48
2 2002 AFG nan 49
3 2003 AFG nan 50
4 2001 CHI 3.0 nan
5 2002 CHI 5.0 nan
6 2003 CHI 7.0 nan
7 2001 USA nan 220
8 2002 USA 4.0 250
9 2003 USA 2.5 280

如果没有任何给定变量的数据(即所有年份的值都缺失),我想删除国家/地区。

在上面的示例表中,我想删除 AFG(因为它遗漏了所有通货膨胀值)和 CHI(遗漏了 GDP)。我不想仅仅因为缺少一年就放弃观察 #7。

最好的方法是什么?

【问题讨论】:

  • 你能举一个之前和预期输出的例子吗?
  • 嘿,当然。我已将问题编辑得更清楚。

标签: python pandas dataframe loops


【解决方案1】:

这应该通过过滤在(通货膨胀,GDP)之一中具有 nan 的所有值来工作:

(
    df.groupby(['country'])
    .filter(lambda x: not x['inflation'].isnull().all() and not x['GDP'].isnull().all())
)

注意,如果您有两个以上的列,您可以使用更通用的版本:

df.groupby(['country']).filter(lambda x: not x.isnull().all().any())

如果您希望它使用特定的年份范围而不是所有列,您可以设置一个掩码并稍微更改代码:

mask = (df['year'] >= 2002) & (df['year'] <= 2003) # mask of years
grp = df.groupby(['country']).filter(lambda x: not x[mask].isnull().all().any())

【讨论】:

  • 这成功了!非常感谢!!有可能在几年内操纵它吗?如果我的总范围是 1980-2000,并且我想删除 x.isnull() 范围内的所有(比如说)1980-1990。
  • @JoaoPedroBastos 是的,确实,您需要根据您需要的年份创建一个掩码(这也可以是您需要的任何条件),然后将其应用于 lambda 表达式中的x。我已经用一个例子更新了我的答案。
【解决方案2】:

你也可以试试这个:

# check where the sum is equal to 0 - means no values in the column for a specific country
group_by = df.groupby(['country']).agg({'inflation':sum, 'GDP':sum}).reset_index()

# extract only countries with information on both columns
indexes = group_by[ (group_by['GDP'] != 0) & ( group_by['inflation'] != 0) ].index
final_countries = list(group_by.loc[ group_by.index.isin(indexes), : ]['country'])

# keep the rows contains the countries

df = df.drop(df[~df.country.isin(final_countries)].index)

【讨论】:

    【解决方案3】:

    您可以将数据框从长调整为宽,删除空值,然后再转换回宽。

    要从长转换为宽,您可以使用pivot functionsSee this question too.

    这里是删除空值的代码,在它被重塑之后:

    df.dropna(axis=0, how= 'any', thresh=None, subset=None, inplace=True) # Delete rows, where any value is null
    

    要转换回 long,可以使用 pd.melt。

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 2013-04-20
      • 2013-11-03
      • 2021-03-31
      • 1970-01-01
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多