Retrieving only one element of a tuple when the tuple is the value of a dictionary

Viewed 23

I am trying to map a column of my df with a dictionary, where the dictionary contains tuples as values. I want to be able to only return the first value of the tuple in the output column. Is there a way to do that?

The situation:

d = {'key1': (1, 2, 3)}
df['lookup_column'] = 'key1'
df['return_column'] = df['lookup_column'].map(d)

Output:

df['return_column'] = (1, 2, 3)

Adding this returns an error:

df['return_column'] = df['return_column'][0]

Running this instead also returns an error:

df['return_column'] = df['lookup_column'].map(d[0])

The desired outcome:

df['return_column'] = 1

Thank you!

1 Answers

Use str for first element of Iterable, here tuple - it return NaN if no match:

df['return_column'] = df['return_column'].str[0]

All together:

df = pd.DataFrame({'lookup_column':['key1','key2']})

d = {'key1': (1, 2, 3)}
df['return_column1'] = df['lookup_column'].map(d)
df['return_column2'] = df['lookup_column'].map(d).str[0]

Second alternative with dict.get for default value if no match, here is ouput tuple so is possible use tuple (np.nan,):

df['return_column4'] = df['lookup_column'].map(lambda x: d.get(x, (np.nan,)))
df['return_column5'] = df['lookup_column'].map(lambda x: d.get(x, (np.nan,))[0])
print (df)
  lookup_column return_column1  return_column2 return_column4  return_column5
0          key1      (1, 2, 3)             1.0      (1, 2, 3)             1.0
1          key2            NaN             NaN         (nan,)             NaN
Related