0

Would like to replace every character with another specific character in panda df['column'] or create a new column with new output. Replace all K with B, 1 to 4, 2 to 3, 3 to 8.

Original column values:

0    K123D
1    K312E
2    K231G

Output:

0    B438D
1    B843E
2    B384G
Juxcy
  • 15
  • 3

2 Answers2

2

Check 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
BENY
  • 317,841
  • 20
  • 164
  • 234
1

You could use 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

    data    res
0  K123D  B438D
1  K312E  B843E
2  K231G  B384G
Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76