Home > Net >  How to create a new list based on the null values of a data frame and list of values?
How to create a new list based on the null values of a data frame and list of values?

Time:05-19

I have a data frame and list op like below.

data = {'Name': ['Tom', 'Joseph', 'Krish', 'John'], 'Age': [20, np.nan, 19, np.nan]}  
df1=pd.DataFrame(data)
print(df1)
Name    Age
Tom     20.0
Joseph  NaN
Krish   19.0
John    NaN
op=[1,2]

Now I want to create create a new list based on the column 'age'. If the column age has a value then the new list li should append op first value and if the column age has a null then the new list should append the value at that position as null. How can I achieve this? Though I tried to loop through every row to create list but the output is wrong and it takes a loot of time to run as I am lopping through every row.

li=[]    
for k in range(len(df1)) :
    if df1.loc[k,'Age']== np.nan:
        print('i')
        li.append(np.nan)
    else:
        for j in op:
            li.append(j)
print(li)

output:- [1, 2, 1, 2, 1, 2, 1, 2]

Execpted output:-

[1,np.nan,2,np.nan]

CodePudding user response:

Assuming the size of op is necessarily that of the non-nan values of Age:

s = df1['Age'].copy()
op=[1,2]
s[s.notna()] = op
out = s.to_list()

output: [1.0, nan, 2.0, nan]

  • Related