4

I have a pandas dataframe and I need to modify all values in a given string column. Each column contains string values of the same length. The user provides the index they want to be replaced for each value

  • for example: [1:3] and the replacement value "AAA".
  • This would replace the string from values 1 to 3 with the value AAA.

How can I use the applymap(), map() or apply() function to get this done?


SOLUTION: Here is the final solution I went off of using the answer marked below:

import pandas as pd

df = pd.DataFrame({'A':['ffgghh','ffrtss','ffrtds'],
                     #'B':['ffrtss','ssgghh','d'],
                     'C':['qqttss',' 44','f']})
print df
old = ['g', 'r', 'z']
new = ['y', 'b', 'c']
vals = dict(zip(old, new))

pos = 2
for old, new in vals.items():
    df.ix[df['A'].str[pos] == old, 'A'] = df['A'].str.slice_replace(pos,pos + len(new),new)
print df

2 Answers 2

15

Use str.slice_replace:

df['B'] = df['B'].str.slice_replace(1, 3, 'AAA')

Sample Input:

   A         B
0  w   abcdefg
1  x   bbbbbbb
2  y   ccccccc
3  z  zzzzzzzz

Sample Output:

   A          B
0  w   aAAAdefg
1  x   bAAAbbbb
2  y   cAAAcccc
3  z  zAAAzzzzz
Sign up to request clarification or add additional context in comments.

3 Comments

@root - great answer, is it possible to add a condition to this as well, so say if position 1 is "A" replace with "B"?
Do you just have one condition, like an if-else statement, or multiple conditions, like an if-elif-else statement?
@root multiple: example let's say the value is 'abcdef'. I need to replace position 3 in the string if values are ['a','b','c'] to match ['d','e','f'] where index 0 of list 1 matched the replace value in list 2.
3

IMO the most straightforward solution:

In [7]: df
Out[7]:
        col
0   abcdefg
1   bbbbbbb
2   ccccccc
3  zzzzzzzz

In [9]: df.col = df.col.str[:1] + 'AAA' + df.col.str[4:]

In [10]: df
Out[10]:
        col
0   aAAAefg
1   bAAAbbb
2   cAAAccc
3  zAAAzzzz

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.