【问题标题】:Row comma removal in pythonpython中的行逗号删除
【发布时间】:2018-12-29 14:24:31
【问题描述】:

我有一个如下所示的数据集:

Id          Product                   Age
001         soup,macaroni,             23
002         bread,milk,butter,         18
003         Bread,                     20

我想删除每个产品末尾的逗号,使其看起来像这样:

Id          Product                   Age
001         soup,macaroni             23
002         bread,milk,butter         18
003         Bread                     20

【问题讨论】:

标签: python python-2.7 pandas numpy


【解决方案1】:

使用str.rstrip(",")

例如:

import pandas as pd
df = pd.DataFrame({"Product": ["soup,macaroni,", "bread,milk,butter,", "Bread,"]})
df["Product"] = df["Product"].str.rstrip(",")
print(df)

输出:

             Product
0      soup,macaroni
1  bread,milk,butter
2              Bread

【讨论】:

  • 非常感谢大家,我尝试了所有解决方案,他们都设法解决了我的问题。
【解决方案2】:

假设您的数据框是 df。

执行以下操作

df["Product"] = df["Product"].apply(lambda x:x.strip(","))

【讨论】:

    【解决方案3】:

    可以str.slice 直到最后一个值

    df.Product.str.slice(0, -1)
    
    
    0        soup,macaroni
    1    bread,milk,butter
    2                Bread
    Name: Product, dtype: object
    

    【讨论】:

      猜你喜欢
      • 2021-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-11
      • 1970-01-01
      • 2021-03-21
      • 1970-01-01
      相关资源
      最近更新 更多