2

I want to compare the following dictionary key:

{('F123', 1): 'R'}

To the index of the following dataframe ('F123', 1):

Connector Pin   Connector   Pin          Adj.         Color        
 F123      1        F123    1         [2, 6, 7]        NaN

If the dictionary key is equal to the dataframe index ('F123', 1) I want copy the dictionary value ('R') into the color column associated with the matching index. Both the dictionary and dataframe have a number of rows but for explanations sake I included only one of each. Speed doesn't matter as the data set is not big enough to matter.

if(df.index == dict.key()):
    df['Color'] = dict.value()

I am struggling syntactically on how to approach this problem.

update: I attempted this below (which I know is wrong). Still trying to nail down how to test all dict. keys one by one without hardcoding it in.

s = df.iterrows(pd.Series(dict.keys()))
df['Color'] = s
MaxB
  • 428
  • 1
  • 8
  • 24

1 Answers1

3

Make a Series from the dictionary and then assign the Color column to that:

In [11]: df
Out[11]:
       Connector  Pin Connector.1 Pin.1 Adj.  Color
F123 1      F123    1         [2,    6,   7]    NaN

In [12]: s = pd.Series({('F123', 1): 'R'})

In [13]: df["Color"] = s

In [14]: df
Out[14]:
       Connector  Pin Connector.1 Pin.1 Adj. Color
F123 1      F123    1         [2,    6,   7]     R
Andy Hayden
  • 359,921
  • 101
  • 625
  • 535
  • So this works, but I am trying to do it for an entire list of different keys/indices. Instead of hard coding the dictionary key into the series is it possible to do some sort of iteration and go from top to bottom? – MaxB Jan 29 '19 at 21:31
  • @MaxB if you have a larger dictionary `{('F123', 1): 'R', ('F456', 2): 'G'}` this will just work, no need for explicit iteration. – Andy Hayden Jan 29 '19 at 21:35
  • Could I please trouble you for a moment to have a look at this question? [Inserting list into a cell - why does loc ACTUALLY work here?](https://stackoverflow.com/questions/54400137/inserting-list-into-a-cell-why-does-loc-actually-work-here) I have a feeling you might be able to weigh in here. – cs95 Jan 30 '19 at 07:50