【问题标题】:replacing ? and | symbols from a string object in a column in a pandas dataframe using loc and replace [duplicate]更换?和 |使用 loc 并替换 pandas 数据框中列中的字符串对象的符号
【发布时间】:2020-09-26 22:01:56
【问题描述】:

我第一次发帖-请善待。我真的一直在寻找和寻找正确的答案,并且尝试了所有我能找到的选项。谷歌搜索错误以尝试调整代码。我已经看过转义字符了。

我有一个带有名为 Page 的列的 pandas 数据框。这是网页名称列表(不是网址)。

所以目前它们以 3 种格式编写:

  1. 回家?家 ?页面名称1
  2. 首页 |主页 |页面名称2
  3. 主页名称3

我希望它们都被格式化为数字 3。

我正在尝试从该列中的字符串对象中删除字符,但保留其余代码。

我用过这个:

df.loc[df['Page'].str.replace(('\?|\|'), ''), Regex=True, Inplace=True]

但我得到了输出:

File "<ipython-input-80-2c616b171200>", line 2
df['page']=df.loc[df['Page'].str.replace(('\?|\\'), ''), Regex=True, Inplace=True]
SyntaxError: invalid syntax

如果我使用它,输出相同:

df['page']=df.loc[df['Page'].str.replace(('\?|\|'), ''), Regex=True, Inplace=True]

我已经尝试了其他选项,例如:

x=pd.Series['Page']
x.str.replace('\?|\|','',regex = True, inplace=True)

但这给了我: TypeError Traceback (most recent call last) &lt;ipython-input-70-6563d5fa5d40&gt; in &lt;module&gt; 1 #clean up page names ----&gt; 2 x=pd.Series['Page'] 3 x.str.replace('\?|\|','',regex = True, inplace=True) TypeError: 'type' object is not subscriptable

有人可以帮忙吗?

谢谢

米兹

【问题讨论】:

标签: python pandas


【解决方案1】:

快到了。试试这个——我稍微调整了你的代码。

df['page'] = df['page'].str.replace(r'\?|\\', '', regex=True)
``

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-11
    • 1970-01-01
    • 2018-03-02
    • 2022-09-23
    • 2021-04-30
    • 2018-10-20
    • 1970-01-01
    • 2012-12-30
    相关资源
    最近更新 更多