制作字符串列的副本,并根据某些值切割字符串

发布于 2025-01-21 11:10:48 字数 435 浏览 2 评论 0原文

我有一个带有Python中安装KKS编码的列的数据框。

KKS编码看起来像这样:

1BLA43AA030 1bor53ar021 1BHY28UI021

我想制作一个新列,其中字符串只有相关信息。有时,代码需要一个数字,但通常不需要。所需的数字是在指定某个对象的3二元字母之后给出的。像这样:

bla 鲍 bhy2

我用完整的KKS编码剪切

df_1['KKS'] = df_1.Object.str[1:4]

,但是对于某些字符串,我需要它是

df_1['KKS'] = df_1.Object.str[1:5]

我的如果不起作用,请帮助

I have a DataFrame with a column with installation KKS-codes in Python.

The KKS-codes look like this:

1BLA43AA030
1BOR53AR021
1BHY28UI021

I want to make a new column where the string only has the relevant information. sometimes the code requires a number but it usually doesn't. The required number is given after the 3digit letter which specify the certain object. like this:

BLA
BOR
BHY2

I cut the full KKS-codes with

df_1['KKS'] = df_1.Object.str[1:4]

but for certain strings i need it to be

df_1['KKS'] = df_1.Object.str[1:5]

My if-statements don't work, please help

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

痴者 2025-01-28 11:10:48

我不完全理解你的意思

所需的数字是在指定某个对象的3Digit字母之后给出的。

如果您可以用示例进一步解释这一点,我可以提供更多帮助。否则,这就是您可以将函数应用于dataframe中的一行的方式:

import pandas as pd

def test_for_four(s: str) -> bool:
    third_digit_letter = s[4]
    if third_digit_letter != "2":
        return True
    return False

def split_kks_code(s: str) -> str:
    if test_for_four(s):
        return s[1:4]
    return s[1:5]

df = pd.DataFrame([{'KKS-Code': '1BLA43AA030'},
                   {'KKS-Code': '1BOR53AR021'},
                   {'KKS-Code': '1BHY28UI021'}])

df['KKS'] = df['KKS-Code'].apply(split_kks_code)

I dont fully understand what you mean by

The required number is given after the 3digit letter which specify the certain object.

If you can explain this further with examples I can help more. Otherwise, this is how you can apply a function to a row in a dataframe:

import pandas as pd

def test_for_four(s: str) -> bool:
    third_digit_letter = s[4]
    if third_digit_letter != "2":
        return True
    return False

def split_kks_code(s: str) -> str:
    if test_for_four(s):
        return s[1:4]
    return s[1:5]

df = pd.DataFrame([{'KKS-Code': '1BLA43AA030'},
                   {'KKS-Code': '1BOR53AR021'},
                   {'KKS-Code': '1BHY28UI021'}])

df['KKS'] = df['KKS-Code'].apply(split_kks_code)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文