soom
soom

Reputation: 29

Add partial data from dictionary to a dataframe

I have a data frame df with columns = [A, B, C, D, E, F, G]. Currently all values are np.nanexcept 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:

A B C D E F G

Nan Nan Nan Nan Nan "Country" "City"

After:

A B C D E F G

1 3 Nan 4 Nan "Country" "City"

Upvotes: 1

Views: 1248

Answers (2)

anky
anky

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

Quang Hoang
Quang Hoang

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

Related Questions