I have two Dataframes, one large with a lot of missing values, and the second with data to fill in the missing data in the first.
File system examples:
In[34]:
import pandas as pd
import numpy as np
df2 = pd.DataFrame({'A': [1, 1, 1, 2, 2, 2], 'B': [1, 0, 1, 1, 0, 0]})
df = pd.DataFrame({'A': [0, 1, 2, 3, 4, 5], 'B1': [1, np.nan, np.nan, 8, 9, 1],'B2':[1, np.nan, np.nan, 7, 6, 1], 'B3':[1, np.nan, np.nan, 8, 7, 1] })
df=df.set_index(['A'])
df2=df2.set_index(['A'])
In[35]:
df
Out[35]:
B1 B2 B3
A
0 1 1 1
1 NaN NaN NaN
2 NaN NaN NaN
3 8 7 8
4 9 6 7
5 1 1 1
In[36]:
df2
Out[36]:
B
A
1 1
1 0
1 1
2 1
2 0
2 0
so I want to populate df using data from df2, also taking into account that B1 is not B2 when it encounters the second instance in df2. See below the desired result:
In[38]:
df
Out[38]:
B1 B2 B3
A
0 1 1 1
1 1 0 1
2 1 0 0
3 8 7 8
4 9 6 7
5 1 1 1
The NaNs in B1, B2, and B3 for 1 and 2 were filled with data from df2. 1 0 1 for index 1 and 1 0 0 for index 2. Below is my inefficient loop implementation:
In[37]:
count=1
seen=[]
for t in range(0, len(df2)):
if df2.index[t] not in seen:
count=1
seen.append(df2.index[t])
else:
count=count+1
tofill=pd.DataFrame(df2.iloc[t]).transpose()
tofill_dict={"B"+str(count):tofill.B}
df=df.fillna(value=tofill_dict)
, , , . , , ?
, , ? ?