在pandas中基于条件创建一个新列。

huangapple go评论88阅读模式
英文:

Create a new column based on condition in pandas

问题

Name col2 Result
First 2 B
Second A1 A
Three 4 D
Yellow B2 B
英文:

In a column i have numbers and alphabets

Name col2
First 2
Second A1
Three 4
Yellow B2

The output will be

Name col2 Result
First 2 B
Second A1 A
Three 4 D
Yellow B2 B

The new column should give values as if col2 = numbers the result values is from A to Z
if col2 = A1 to A222 then result = A and if col2 = B2 then result = B

答案1

得分: 1

以下是翻译好的内容:

你可以尝试类似下面的代码

    from string import ascii_uppercase
    
    d = {str(i): l for i, l in enumerate(ascii_uppercase, start=1)}
    
    df["Result"] = (
        df["col2"].str.extract("([A-Z])", expand=False).fillna(df["col2"]).replace(d)
    )

输出

    print(df)
    
         Name col2 Result
    0   First    2      B
    1  Second   A1      A
    2   Three    4      D
    3  Yellow   B2      B
英文:

You can try something like below :

from string import ascii_uppercase

d = {str(i): l for i,l in enumerate(ascii_uppercase, start=1)}

df["Result"] = (
    df["col2"].str.extract("([A-Z])", expand=False).fillna(df["col2"]).replace(d)
)

Output :

print(df)

     Name col2 Result
0   First    2      B
1  Second   A1      A
2   Three    4      D
3  Yellow   B2      B

huangapple
  • 本文由 发表于 2023年6月1日 01:43:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/76376074.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定