繁体   English   中英

如何遍历列并按组检查条件

[英]How to iterate over columns and check condition by group

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

指数 国家 通货膨胀 国内生产总值
1 2001年 AFG 48
2 2002年 AFG 49
3 2003年 AFG 50
4 2001年 3.0
5 2002年 5.0
6 2003年 7.0
7 2001年 美国 220
8 2002年 美国 4.0 250
9 2003年 美国 2.5 280

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

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

最好的方法是什么?

这应该通过过滤在(通货膨胀,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())

你也可以试试这个:

# 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)

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

要从长转换为宽,可以使用pivot 函数 也看到这个问题

这是重构后删除空值的代码:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM