AttributeError: 'method_descriptor' object has no attribute 'df_new' in python when replacing string

AttributeError: 'method_descriptor' object has no attribute 'df_new' in python when replacing string

我正在编写一小段代码,以从 pandas 数据框的一列数据中的名称中删除 Web 浏览器版本号。即用字母字符替换包含字母和数字字符的字符串。

我写了:

df_new=(rename())

str.replace.df_new[new_browser]('[.*0-9]',"",regex=True)

我收到这条错误消息,但我不明白它在告诉我什么

AttributeError                            Traceback (most recent call last)
<ipython-input-4-d8c6f9119b9f> in <module>
      3 df_new=(rename())
      4 
----> 5 str.replace.df_new[new_browser]('[.*0-9]',"",regex=True)

AttributeError: 'method_descriptor' object has no attribute 'df_new'

上面的代码在 Jupyter Notebook

中遵循此 code/function
import pandas as pd
import numpy as np
import re

    #write a function to change column names using a dictionary
    
    def rename():
        dict_col = {'Browser':'new_browser', 'Page':'web_page', 'URL':'web_address', 'Visitor ID':'visitor_ID'}
        df = pd.read_csv ('dummy_webchat_data.csv')
        for y in df.columns:
            if y in dict_col:
                df_new=df.rename(columns={y:dict_col}[y])
            
        return df_new

rename()

我一直遇到下次调用时无法识别数据帧更新的问题。通常在 JN 中,我只是不断地对 df 进行修改,它会保留更新。但即使是代码 df_new.head(1) 也需要这样写才能在第一个函数 运行 之后工作,出于某种原因(提到它感觉像一个类似的问题,即使错误消息不同):

df_new=(rename())
df_new.head(1)

有人能帮帮我吗?

最佳

该错误告诉您您没有正确使用 Series.str.replace() 方法。

您有:

str.replace.df_new[new_browser]('[.*0-9]',"",regex=True)

当你想要的是:

df_new[new_browser].str.replace('[.*0-9]',"",regex=True)

看到这个:

>>> import pandas as pd
>>>
>>> s = pd.Series(['a1', 'b2', 'c3', 'd4'])
>>> s.str.replace('[.*0-9]',"",regex=True)
0    a
1    b
2    c
3    d
dtype: object

并将其与此进行比较(这是你得到的,s 这是你的 df_new[new_browser]):

>>> import pandas as pd
>>>
>>> s = pd.Series(['a1', 'b2', 'c3', 'd4'])
>>> str.replace.s('[.*0-9]',"",regex=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'method_descriptor' object has no attribute 's'