简体   繁体   English

替换 Pandas 列中的字符

[英]Replacing characters in Pandas Column

Would like to replace every character with another specific character in panda df['column'] or create a new column with new output.想用 panda df['column'] 中的另一个特定字符替换每个字符,或者用新的 output 创建一个新列。 Replace all K with B, 1 to 4, 2 to 3, 3 to 8.将所有 K 替换为 B,1 到 4、2 到 3、3 到 8。

Original column values:原始列值:

0    K123D
1    K312E
2    K231G

Output: Output:

0    B438D
1    B843E
2    B384G

Check replace检查replace

df.col = df.col.replace({'K':'B','1':'4','3':'8','2':'3'},regex=True)
0    B438D
1    B843E
2    B384G
Name: col, dtype: object

You could use str.translate :您可以使用str.translate

df = pd.DataFrame(data=["K123D",
                        "K312E",
                        "K231G"], columns=['data'])

table = str.maketrans({'K' : 'B', '1' : '4', '2' : '3', '3': '8'})

df['res'] = df['data'].str.translate(table)

print(df)

Output Output

    data    res
0  K123D  B438D
1  K312E  B843E
2  K231G  B384G

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM