Reputation: 15
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
Upvotes: 0
Views: 877
Reputation: 61910
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
Upvotes: 2
Reputation: 323226
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
Upvotes: 2