gpt4 book ai didi

python - 如果特定年份的列中有 NaN 值,则删除行

转载 作者:行者123 更新时间:2023-12-05 02:26:33 32 4
gpt4 key购买 nike

我正在尝试删除 2019 年和 2020 年的第 1、2 和 3 列中存在 NaN 值的行。

这是数据框:

col1     col2     col3     col4     year
NaN NaN NaN NaN 2018
NaN NaN NaN NaN 2019
NaN NaN NaN 100 2019
100 200 100 NaN 2020
NaN NaN NaN 200 2020
100 100 150 150 2021

预期结果:

col1     col2     col3     col4     year
NaN NaN NaN NaN 2018
100 200 100 NaN 2020
100 100 150 150 2021

我试过了,但无法正常工作:

df.drop(df[(df['year'] == [2019, 2020]) 
& (df[['col1', 'col2', 'col3']].isnull())].index, inplace=True)

最佳答案

您需要使用 isin检查多个值,以及 all将您的布​​尔 DataFrame 聚合到一个系列中:

# is the year 2019 or 2020?
m1 = df['year'].isin([2019, 2020])
# are all the values in col1/col2/col3 null for a given row?
m2 = df[['col1', 'col2', 'col3']].isnull().all(1)

# invert the above two conditions to select rows to keep
df = df[~(m1&m2)]

# or
# df.drop(df[m1&m2].index, inplace=True)

输出:

    col1   col2   col3   col4  year
0 NaN NaN NaN NaN 2018
3 100.0 200.0 100.0 NaN 2020
5 100.0 100.0 150.0 150.0 2021

关于python - 如果特定年份的列中有 NaN 值,则删除行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73728783/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com