2

I have a Pandas series orders['customer'] that looks like this:

0      {'id': 454543543533, 'email': 'aaaaaa@gmail.com...
1      {'id': 437890767654, 'email': 'bbbbbbbb@mail.com...
2      {'id': 534764345453, 'email': 'ccccccccc@mail.com..
3      {'id': 345436564353, 'email': None, 'accepts_m....
4      {'id': 671341215803, 'email': None, 'accepts_m...
5      {'id': 671317065787, 'email': None, 'accepts_m...

I would like to iterate over the rows of this series and get the first element for each dictionary (id). Moreover I would like to substitute the values in the series with only the id.

I tried many different solutions, last this one, but I cannot make this thing work:

for i in range(len(orders_df['customer'].values.tolist())):
    orders_df['customer'] = orders_df['customer'].values.tolist()[i]
Matteo Ragni
  • 2,837
  • 1
  • 20
  • 34
robsanna
  • 433
  • 1
  • 7
  • 16

1 Answers1

3

Use lambda function with get for match value if dictionary with key id else return default value, here 0:

orders_df = pd.DataFrame({'customer':[{'id': 454543543533, 'email': 'fdgr@gmail.com'}, 
                                      {'id': 437890767654, 'email': 'ereffewf@mail.com'},
                                      {'email': 'ereffewf@mail.com'}]})
print (orders_df)
                                            customer
0    {'id': 454543543533, 'email': 'fdgr@gmail.com'}
1  {'id': 437890767654, 'email': 'ereffewf@mail.c...
2                     {'email': 'ereffewf@mail.com'}

orders_df['customer'] = orders_df['customer'].apply(lambda x: x.get('id', 0))

Or:

orders_df['customer'] = [x.get('id', 0) for x in orders_df['customer']]

print (orders_df)
       customer
0  454543543533
1  437890767654
2             0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks, it works, could you explain me a bit how this works? – robsanna Jul 24 '18 at 08:05
  • @roberto.sannazzaro - Sure, it working because in `Series` are dictionaries and need select `id`, also better is use `get` because if not match (in some row is no `id`) it return None – jezrael Jul 24 '18 at 08:06