1

Consider the following pandas.DataFrame:

>>> import pandas as pd
>>> df = pd.DataFrame({
...     "sym": ["a", "b", "c"],
...     "del": [1, 2, 3]
... })

And consider the following dict:

>>> d = [{"sid": 99, "sym": "b"}, {"sid": 88, "sym": "c"}]

I need to update df's index with the value of sid where sym matches. For this example, my output would like like this:

>>> df
   sym  del
0    a    1
99   b    2
88   c    3

How might I do this?

0

2 Answers 2

2

Use Series.map with dictionary, then replace missing values by original index values:

d = [{"sid": 99, "sym": "b"}, {"sid": 88, "sym": "c"}]

d1 = {x['sym']:x['sid'] for x in d}
df.index = df['sym'].map(d1).fillna(df.index.to_series()).astype(int).rename(None)

print (df)
   sym  del
0    a    1
99   b    2
88   c    3

df = pd.DataFrame({
    "sym": ["a", "b", "c"],
   "del": [1, 2, 3]
}, index=[50,51,52])
print (df)
   sym  del
50   a    1
51   b    2
52   c    3

d = [{"sid": 99, "sym": "b"}, {"sid": 88, "sym": "c"}]

d1 = {x['sym']:x['sid'] for x in d}
df.index = df['sym'].map(d1).fillna(df.index.to_series()).astype(int).rename(None)

print (df)
   sym  del
50   a    1
99   b    2
88   c    3
Sign up to request clarification or add additional context in comments.

5 Comments

This returns index as float, not int.
@Stuart - Hmmm, for me not.
This also will reset other indexes. Example if the indexes are [50, 51, 52] the example code will return indexes of [0, 51, 52]. Can only mutate the matching rows.
@JasonStrimpel - For me working correct, edited answer.
Yes I see what I did. Works well
1

here is one way using merge after converting the list of dict to a dataframe:

m = df.merge(pd.DataFrame(d),on='sym',how='left')
df.index = m['sid'].fillna(df.index.to_series()).astype(int).rename(None)
print(df)

   sym  del
0    a    1
99   b    2
88   c    3

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.