【问题标题】:Getting this typeError: expected string or bytes-like object [closed]获取此类型错误:预期的字符串或类似字节的对象[关闭]
【发布时间】:2019-06-29 13:05:49
【问题描述】:

代码:

import pandas as pd
import numpy as np
import re

df=pd.read_csv('twitDB.csv',header=None, sep=',',error_bad_lines=False,encoding='utf-8')

hula=df[[0,1,2,3]]
hula=hula.fillna(0)
hula['tweet'] = hula[0].astype(str) +hula[1].astype(str)+hula[2].astype(str)+hula[3].astype(str) 
dhole=hula["tweet"]


dhole = re.sub('\s+', ' ',dhole )

得到这个:

错误:预期的字符串或类似字节的对象

【问题讨论】:

  • 请包含完整错误信息。
  • Dhole 只是一个参数。
  • print(repr(dhole)) 0 1495596971.6034188::#Automotive #Auto EBC Gree... 1 1495596972.330948::新的免费库存照片 cit... 2 1495596972.775966::eBay: 1974 Volkswagen Beetl ...名称:推文,数据类型:对象
  • 请修改您的问题,而不是在 cmets 中放入代码 sn-ps 和列出错误消息。

标签: python pandas


【解决方案1】:

我认为您需要Series.replaceSeries.str.replace,因为与Series(数组)和re.sub 一起使用标量:

dhole = dhole.replace('\s+', ' ', regex=True)
#or
dhole = dhole.str.replace('\s+', ' ')

示例:

>>> hula = pd.DataFrame({'tweet':['ss      ddd s   ss','d         d','f       t       y']})
>>> dhole=hula["tweet"]
>>> print (dhole)
0    ss      ddd s   ss
1           d         d
2     f       t       y
Name: tweet, dtype: object

>>> dhole = dhole.replace('\s+', ' ', regex=True)
>>> print (dhole)
0    ss ddd s ss
1            d d
2          f t y
Name: tweet, dtype: object

>>> dhole = dhole.str.replace('\s+', ' ')
>>> print (dhole)
0    ss ddd s ss
1            d d
2          f t y
Name: tweet, dtype: object

【讨论】:

  • 谢谢。未来的小建议 - how to provide a great pandas example。祝你好运!
  • link有人知道这个问题的答案吗?
  • 我现在检查一下。什么是问题?是否有必要拆分所有单词并在每个 cel 中创建单词列表?你能解释更多吗?
  • 是的,我想拆分所有单词。
  • 所以看来ho = ho.to_frame(name=None) a=ho.to_string(buf=None, columns=None, col_space=None, header=True, index=True, na_rep='NaN', formatters=None, float_format=None, sparsify=False, index_names=True, justify=None, line_width=None, max_rows=None, max_cols=None, show_dimensions=False)需要ho = ho.str.split()
猜你喜欢
  • 2019-12-13
  • 2017-01-19
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2020-11-19
  • 2020-08-24
  • 2017-09-29
相关资源
最近更新 更多