Python替换csv文件中的字符串

时间:2019-03-13 10:42:27

标签: python pandas csv

我想向现有的.csv文件添加一个新列tidy_tweet,该文件实现了remove_pattern功能

def remove_pattern(input_txt, pattern):
    r = re.findall(pattern, input_txt)
    for i in r:
        input_txt = re.sub(i, '', input_txt)
    return input_txt   

我写了这些代码行

data  = pd.read_csv(filepath_or_buffer='stockerbot-export.csv', error_bad_lines=False)
data['tidy_tweet'] = np.vectorize(remove_pattern)(data['text'], "@[\w]*")

我遇到以下错误

MemoryError                               Traceback (most recent call last)
<ipython-input-15-d6e7e950d5b9> in <module>()
----> 1 data['tidy_tweet'] = np.vectorize(remove_pattern)(data['text'], "@[\w]*")

~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in __call__(self, *args, **kwargs)
   1970             vargs.extend([kwargs[_n] for _n in names])
   1971 
-> 1972         return self._vectorize_call(func=func, args=vargs)
   1973 
   1974     def _get_ufunc_and_otypes(self, func, args):

~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in _vectorize_call(self, func, args)
   2049 
   2050             if ufunc.nout == 1:
-> 2051                 res = array(outputs, copy=False, subok=True, dtype=otypes[0])
   2052             else:
   2053                 res = tuple([array(x, copy=False, subok=True, dtype=t)

MemoryError: 

我无法理解该错误。需要帮助。

1 个答案:

答案 0 :(得分:1)

该错误是不言自明的,您在处理大量数据并对其进行循环时会耗尽内存。有一个更简单的解决方案尝试一下。

data['tidy_tweet'] = data['text'].str.replace('@[\w]*', '',regex=True)

如果您使用的熊猫版本较旧,即regex=True的熊猫,则删除0.23.0

documentation

示例:

enter image description here