剥离pandas数据帧索引'\ n'和空格

时间:2017-02-11 17:17:10

标签: python pandas

从html响应中获取数据并通过pandas Dataframe通过以下代码提供数据后,我转置数据并打印结果。

r1 = bs4.BeautifulSoup(r.text, 'lxml').prettify()
r3 = pandas.read_html(r1, header=None, index_col=None)[0]
r3.dropna(inplace=True)

r4 = pandas.DataFrame.transpose(r3)

r5 = r4.index

print(r5)

我得到以下结果。

Index(['\n                     ',
       '\n                      2006-12\n                     ',
       '\n                      2007-12\n                     ',
       '\n                      2008-12\n                     ',
       '\n                      2009-12\n                     ',
       '\n                      2010-12\n                     ',
       '\n                      2011-12\n                     ',
       '\n                      2012-12\n                     ',
       '\n                      2013-12\n                     ',
       '\n                      2014-12\n                     ',
       '\n                      2015-12\n                     ',
       '\n                      TTM\n                     '],
      dtype='object')

如何删除此索引中的所有'\n'white spaces以获取数字和TTM?

1 个答案:

答案 0 :(得分:1)

IIUC你可以这样做:

In [98]: i
Out[98]:
Index(['\n                     ', '\n                      2006-12\n                     ', '\n                      2007-12\n
       ',
       '\n                      2008-12\n                     ', '\n                      2009-12\n                     ', '\n
        2010-12\n                     ',
       '\n                      2011-12\n                     ', '\n                      2012-12\n                     ', '\n
        2013-12\n                     ',
       '\n                      2014-12\n                     ', '\n                      2015-12\n                     ', '\n
        TTM\n                     '],
      dtype='object')

In [99]: i = i.str.replace(r'[\n\s]+', '')

In [100]: i
Out[100]: Index(['', '2006-12', '2007-12', '2008-12', '2009-12', '2010-12', '2011-12', '2012-12', '2013-12', '2014-12', '2015-12', 'TTM'], d
type='object')

来自@Joe Lin的更好解决方案:

In [103]: i.str.strip()
Out[103]: Index(['', '2006-12', '2007-12', '2008-12', '2009-12', '2010-12', '2011-12', '2012-12', '2013-12', '2014-12', '2015-12', 'TTM'], d
type='object')