【问题标题】:How to rename values in column having a specific separation symbols?如何重命名具有特定分隔符号的列中的值?
【发布时间】:2021-12-15 05:23:55
【问题描述】:

我的 DataFrame 中的值如下所示:

id                         val
big_val_167                80
renv_100                   100
color_100                  200
color_60/write_10          200

我想删除 _numeric 之后 id 列的值中的所有内容。所以想要的结果必须是这样的:

id             val
big_val        80
renv           100
color          200
color          200

如何做到这一点?我知道str.replace()可以用,但是不明白正则表达式部分怎么写。

【问题讨论】:

  • 欢迎。您可以使用re.search,正如我在下面的回答中所述。

标签: python pandas string dataframe


【解决方案1】:

你可以使用regex(re.search)找到第一个出现的_+数字,然后就可以解决问题了。

代码:

import re
import pandas as pd

def fix_id(id):
    # Find the first occurence of: _ + digits in the id:
    digit_search = re.search(r"_\d", id)
    return id[:digit_search.start()]

# Your df
df = pd.DataFrame({"id": ["big_val_167", "renv_100", "color_100", "color_60/write_10"],
                   "val": [80, 100, 200, 200]})

df["id"] = df["id"].apply(fix_id)
print(df)

输出:

        id  val
0  big_val   80
1     renv  100
2    color  200
3    color  200

【讨论】:

    猜你喜欢
    • 2019-03-19
    • 1970-01-01
    • 1970-01-01
    • 2022-07-28
    • 1970-01-01
    • 2022-06-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    相关资源
    最近更新 更多