-2

I need to apply a function for each of the elements of a collections namedtuple.

Product = collections.namedtuple('Product', [
        'ticker_symbol', 'entity', 'unique_id', 'as_of_date', 'company_name',
        'followers', 'items', 'linkedin', 'industry', 'date_added',
        'date_updated', 'description', 'website', 'sector', 'ticker_industry'
    ])

response_rows = response_items.get('rows')
for response_row in response_rows:
    logging.info(response_row)
    results.append(Company(*response_row))
  return results

I want to apply to each of the elements in Company namedtuple the following function:

def _ToString(value):
  if not value:
    logging.warning('Empty value')
    return None

  if isinstance(value, unicode):
    return value.encode('utf-8')
  else:
    return str(value)
gogasca
  • 9,283
  • 6
  • 80
  • 125
  • Oh hello I see some of my code there. – cs95 Jun 06 '18 at 03:52
  • Have you tried anything at all? Have you tried iterating over the tuple and applying the function? – juanpa.arrivillaga Jun 06 '18 at 03:54
  • I wanted to check if there is a function similar to apply function to column in pandas. I just iterated results.append(Product(*[_ToString(x) for x in response_row])) – gogasca Jun 06 '18 at 04:08
  • So, you *have* a solution. What is wrong with that solution? If you are asking about methods available on `namedtuples`, you could check the [documentation](https://docs.python.org/3/library/collections.html). But you'll find no such method. – juanpa.arrivillaga Jun 06 '18 at 04:12

1 Answers1

0

I ended up using this line:

results.append(Company(*[_ToString(x) for x in response_row]))
gogasca
  • 9,283
  • 6
  • 80
  • 125