41

Pandas テーブル内に (Web ページへの) リンクを挿入したいので、IPythonノートブックに表示されているときにリンクを押すことができます。

私は次のことを試しました:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame(range(5), columns=['a'])

In [3]: df['b'] = df['a'].apply(lambda x: 'http://example.com/{0}'.format(x))

In [4]: df
Out[4]:
   a                     b
0  0  http://example.com/0
1  1  http://example.com/1
2  2  http://example.com/2
3  3  http://example.com/3
4  4  http://example.com/4

ただし、URL はテキストとして表示されるだけです。

IPython HTML オブジェクトも使用してみました:

In [5]: from IPython.display import HTML

In [6]: df['b'] = df['a'].apply(lambda x:HTML('http://example.com/{0}'.format(x)))

In [7]: df
Out[7]:
   a                                                 b
0  0  <IPython.core.display.HTML object at 0x0481E530>
1  1  <IPython.core.display.HTML object at 0x0481E770>
2  2  <IPython.core.display.HTML object at 0x0481E7B0>
3  3  <IPython.core.display.HTML object at 0x0481E810>
4  4  <IPython.core.display.HTML object at 0x0481EA70>

ただし、オブジェクトの表現のみが表示されます。

他のアイデアはありますか?


alko は正しい答えを得ました。セルの幅はデフォルトで制限されており、長い HTML コードは切り捨てられることを追加したかっただけです。

<a href="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0">xxx</a>

これになります:

<a href="aaaaaaaaaaaaaaaaaaaaaa...

となり、正しく表示されません。(ただし、テキスト xxx は短く、セルに収まります。)

設定してバイパスしました:

pd.set_printoptions(max_colwidth=-1)
4

4 に答える 4

71

Pandas オブジェクト全体をHTML オブジェクトとして表現する必要があると思います。

In [1]: from IPython.display import HTML

In [2]: df = pd.DataFrame(list(range(5)), columns=['a'])

In [3]: df['a'] = df['a'].apply(lambda x: '<a href="http://example.com/{0}">link</a>'.format(x))

In [4]: HTML(df.to_html(escape=False))

申し訳ありませんが、手元に IPython がなく、出力が正しいかどうかを確認できません。

于 2013-11-18T09:03:35.943 に答える