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

标签 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'空格,只保留数字和 TTM?

最佳答案

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')

关于python - 剥离 pandas 数据帧索引 '\n' 和空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42178803/

相关文章:

python - 如何使用 Selenium 和 phantomjs webdriver 正确传递基本身份验证(每次点击)

python - 如何在 python 中绘制多边形?

python - Google BigQuery Schema 冲突(pyarrow 错误)与使用 load_table_from_dataframe 的数字数据类型

python - Series 的真值在数据框中不明确

python - 确保对象列表仅包含唯一项的大多数 pythonic 方法

python - 如何从 Pandas DataFrame 中提取和求和唯一单词

python - 如何使用 NaN 值计算 Pandas 的时差

python-2.7 - Pandas :一种使用namedtuple列表初始化数据帧的干净方法

python - 移植pickle py2到py3 字符串变成字节

python - 如何在Python中使用pandas访问导入的csv文件中的元素?