Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
372 views
in Technique[技术] by (71.8m points)

python - Negation in np.select() condition

Here is my code:

import pandas as pd
import numpy as np

df = pd.DataFrame({ 'var1': ['a', 'b', 'c',np.nan, np.nan],
                   'var2': [1, 2, np.nan , 4, np.nan]
                 })



conditions = [
    (not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"]))),
    (pd.isna(df["var1"])) & (pd.isna(df["var2"]))]

choices = ["No missing", "Both missing"]

df['Result'] = np.select(conditions, choices, default=np.nan)

Output:

  File "C:ProgramDataAnaconda3libsite-packagespandascoregeneric.py", line 1478, in __nonzero__
    f"The truth value of a {type(self).__name__} is ambiguous. "

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

Problem is with line (not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"]))). This line should give TRUE when in both var1 and var2 in not a NaN value. Problem here is with negation, because with conditions without negation there is no problem.

Question: How can to correct (not(pd.isna(df["var1"]))) & (not(pd.isna(df["var2"]))) line so in case when in both var1 and var2 in not a NaN value the condition should give TRUE?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try:

conditions = [(~pd.isna(df["var1"]) & ~pd.isna(df["var2"])),
               (pd.isna(df["var1"]) &  pd.isna(df["var2"]))]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...