asdfkjasdfjk
asdfkjasdfjk

Reputation: 3894

Pad a column of strings in a pandas dataframe

I have a pandas dataframe with string in a column like this

 id   b
  1   this is string1
  1   this is string2
  1   this is string3
  1   this is string4

Now I want to remove the first character(t) from each cell of column b. I also need to add a character s at the beginning and end of this column. So the output should look like this

 id   b
  1   shis is string1s
  1   shis is string2s
  1   shis is string3s
  1   shis is string4s

I know I can iterate over each row and do these operations but I was hopping there might be some efficient way of doing this. Maybe I can apply same operation on all cells of column b at once?

Upvotes: 2

Views: 1387

Answers (3)

PIG
PIG

Reputation: 602

You can replace the first and last character like this:

df['b'] = df.b.str.replace('^.|$', 's')

Upvotes: 0

cs95
cs95

Reputation: 402523

A more concise/flexible approach with df.apply:

df.b = df.b.str[1:].apply('s{}s'.format)
print(df)

   id                 b
0   1  shis is string1s
1   1  shis is string2s
2   1  shis is string3s
3   1  shis is string4s

And, to replace just the first occurrence of t, use pd.Series.str.replace:

df.b = df.b.str.replace('t', '', 1).apply('s{}s'.format)
print(df)

   id                 b
0   1  shis is string1s
1   1  shis is string2s
2   1  shis is string3s
3   1  shis is string4s

Upvotes: 4

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

In [6]: df.b = 's' + df.b.str[1:] + 's'

In [7]: df
Out[7]:
   id                 b
0   1  shis is string1s
1   1  shis is string2s
2   1  shis is string3s
3   1  shis is string4s

if you want to replace a first occurance of t:

In [14]: df
Out[14]:
   id              b
0   1           test
1   2         a test
2   3  no occurences

In [15]: df.b = df.b.str.replace('t', '-', n=1)

In [16]: df
Out[16]:
   id              b
0   1           -est
1   2         a -est
2   3  no occurences

Upvotes: 3

Related Questions