mardi 4 août 2015

Python & Pandas: Add a link to existing field

In my pandas table, the url is in ['douban_info']['alt'], I want to use it to turn the existing field ['db_rating'] into a link, maybe something like

pd_data['db_rating'] = '<a href=pd_data['douban_info']['alt'] >pd_data['db_rating']</a>'

but this above certainly doesn't work, I can only do something like:

from IPython.display import HTML
pd.set_option('max_colwidth', 500)
# link is in ['douban_info']['alt']
pd_data['link'] = pd_data['douban_info'].apply(lambda x:  x['alt'])
pd_data['a'] = pd_data['link'].apply(lambda x: '<a href="{0}">link</a>'.format(x))
# drop redundent info to make table look better
pd_data = pd_data.drop('douban_info', 1)
pd_data = pd_data.drop('omdb_info', 1)
pd_data = pd_data.drop('link', 1)
HTML(pd_data[0:5].to_html(escape=False))

This can only add a new a field, which produces enter image description here

There're certain thing that's really annoying:

  1. To get data from json, I only know to use pd_data['link'] = pd_data['douban_info'].apply(lambda x: x['alt'])

  2. I only know to use info from one field to another. In the case above, from link to a. I don't know how to use link and incoporate it into db_rating, how can I do it?

Aucun commentaire:

Enregistrer un commentaire