Got the Following Dataframe:
A B
Temp1 1
Temp2 2
NaN NaN
NaN 4
Since the A nad B are correlated, I am able to create new column where I have calculated the nan value of A and B and form a tuple:
A B C
Temp1 1 (1,Temp1)
Temp2 2 (2, Temp2)
NaN NaN (3, Temp3)
NaN 4 (4, Temp4)
Now I have to drop the column C and fill the Nan value corrosponding to the Columns.
Use Series.fillna
with select values in tuple by indexing with str
, last remove C
column:
#if values are not in tuples
#df.C = df.C.str.strip('()').str.split(',').apply(tuple)
df.A = df.A.fillna(df.C.str[1])
df.B = df.B.fillna(df.C.str[0])
df = df.drop('C', axis=1)
print (df)
A B
0 Temp1 1
1 Temp2 2
2 Temp3 3
3 Temp4 4
Or create DataFrame from C
with DataFrame.pop
for use and remove column, set new columns names and pass to DataFrame.fillna
:
#if values are not in tuples
#df.C = df.C.str.strip('()').str.split(',').apply(tuple)
df[['A','B']] = df[['A','B']].fillna(pd.DataFrame(df.pop('C').tolist(), columns=['B','A']))
print (df)
A B
0 Temp1 1
1 Temp2 2
2 Temp3 3
3 Temp4 4
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.