python - Pandas - Modify string values in each cell -
i have panda dataframe , need modify values in given column. each column contains string value of same length. user provides index want replaced each value: ex: [1:3]
, replacement value "aaa"
.
this replace string values 1 3 value aaa
.
how can use applymap, map or apply function done?
thanks
here final solution went off of using answer marked below:
import pandas 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 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
use str.slice_replace
:
df['b'] = df['b'].str.slice_replace(1, 3, 'aaa')
sample input:
b 0 w abcdefg 1 x bbbbbbb 2 y ccccccc 3 z zzzzzzzz
sample output:
b 0 w aaaadefg 1 x baaabbbb 2 y caaacccc 3 z zaaazzzzz
Comments
Post a Comment