S
S
Sergey Ilyin2021-11-18 17:44:40
Python
Sergey Ilyin, 2021-11-18 17:44:40

How to update pandas dataframe with data from dictionary?

There is a dataframe:

test_dict = {
    'A':1,
    'B':2,
    'C':3,
    'D':None
    }
test_dict_df = pd.DataFrame.from_dict(test_dict.items())
test_dict_df = test_dict_df.rename(columns={0:'name', 1:'value'})

Now I want to add a dictionary to this dataframe:
update_dict = {'D':33}

for i,x in update_dict.items():
    test_dict_df[test_dict_df['name']==i]['value'] = x

But it does not update the dataframe with such a cycle in any way (
I want something like a cycle, because there can be several `keys` in `update_dict`.

Maybe through `apply` somehow it is possible?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Ilyin, 2021-11-18
@sunsexsurf

solution from SO:
```
t = test_dict_df["name"].map(update_dict).dropna()
test_dict_df.loc[t.index, "value"] = t
```

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question