英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论