Reputation: 29
I have a data frame df with columns = [A, B, C, D, E, F, G]
. Currently all values are np.nan
except column F and G which contain "Country" "City" respectively.
I have a dictionary such that dictionary = {A: 1, B: 3, D: 4}
.
I want to add values from dictionary to dataframe such that the values in column A, B, D
is 1, 3, 4
respectively while everything else remains what it was before adding the dictionary.
For example:
before addition df:
Nan Nan Nan Nan Nan "Country" "City"
After:
1 3 Nan 4 Nan "Country" "City"
Upvotes: 1
Views: 1248
Reputation: 75120
Try update:
df =pd.DataFrame(columns = ['A', 'B', 'C', 'D', 'E'])
df.loc[0]=np.nan
A B C D E
0 NaN NaN NaN NaN NaN
d={'A': 1, 'B': 3, 'D': 4}
df.update(pd.Series(d).to_frame().T)
print(df)
A B C D E
0 1 3 NaN 4 NaN
Upvotes: 1
Reputation: 150785
Here:
# empty df:
df = pd.DataFrame(columns=list('ABCDE'))
# append
df.append(pd.Series(d), ignore_index=True)
Output:
A B C D E
0 1.0 2.0 NaN 4.0 NaN
Upvotes: 1