【问题标题】:pandas series to multi-column html熊猫系列到多列html
【发布时间】:2013-05-24 16:23:20
【问题描述】:

我有一个 Pandas 系列(对应于单个记录的较大 DF 切片),我想显示为 html。虽然我可以将 Series 转换为 DataFrame 并使用 .to_html() 函数,但这将导致两列 html 输出。为了节省空间/提供更好的纵横比,我想返回一个四列或六列 HTML 表,其中系列已被包装成两组或三组索引值列,就像这样。

import pandas as pd
s = pd.Series( [12,34,56,78,54,77], index=['a', 'b', 'c', 'd', 'e','f'])
#pd.DataFrame(s).to_html()
#will yield 2 column hmtl-ed output 
# I would like a format like this:
a 12  d 78
b 34  e 54
c 56  f 77

这是我目前拥有的:

x = s.reshape((3,2))
y = s.index.reshape((3,2))
new = [ ]
for i in range(len(x)):
    new.append(y[i])
    new.append(x[i])
 z = pd.DataFrame(new)
 z.T.to_html(header=False, index=False)

有没有我可能错过的更好的方法?

谢谢 扎克cp

【问题讨论】:

  • 需要html还是字符串?
  • 目标是输出到html。因为 DataFrame 已经有一个 to_html 函数,所以我认为使用它是最简单的。但如果你有其他解决方案 - 我全神贯注。

标签: pandas


【解决方案1】:

这更简单。顺序略有不同(跨行读取,而不是向下读取),但我不确定这对您是否重要。

In [17]: DataFrame(np.array([s.index.values, s.values]).T.reshape(3, 4))
Out[17]: 
   0   1  2   3
0  a  12  b  34
1  c  56  d  78
2  e  54  f  77

与您的示例一样,您需要从 HTML 中省略“标题”和索引。

【讨论】:

  • 嗨,丹,虽然格式与我想要的有点不同,但你的方法要好得多。在接受之前,我将再等几分钟,看看是否有其他人加入。
猜你喜欢
  • 2020-06-03
  • 2014-06-15
  • 1970-01-01
  • 2016-08-30
  • 2017-05-23
  • 2014-07-11
  • 2014-06-16
  • 2022-12-10
  • 2016-08-23
相关资源
最近更新 更多