3

I have a pandas dataframe and I would like to modify the values of my first column adding before or after the original value the string " name ". How is the best way to do that.

Here my dataframe :

df

  protein_name  LEN  Start    End
0     Ribosomal_S9:  121      0    121
1     Ribosomal_S8:  129    121    250
2    Ribosomal_L10:  100    250    350
3             GrpE:  166    350    516
4           DUF150:  141    516    657
..              ...  ...    ...    ...
115      TIGR03632:  117  40149  40266
116      TIGR03654:  175  40266  40441
117      TIGR03723:  314  40441  40755
118      TIGR03725:  212  40755  40967
119      TIGR03953:  188  40967  41155

and here what I want to add :

name = "name"

I am not very demanding for what I want, just something like :

df

            protein_name  LEN  Start    End
0     Name Ribosomal_S9:  121      0    121
1     Name Ribosomal_S8:  129    121    250
2    Name Ribosomal_L10:  100    250    350
3             Name GrpE:  166    350    516
4           Name DUF150:  141    516    657
..              ...  ...    ...    ...
115      Name TIGR03632:  117  40149  40266
116      Name TIGR03654:  175  40266  40441
117      Name TIGR03723:  314  40441  40755
118      Name TIGR03725:  212  40755  40967
119      Name TIGR03953:  188  40967  41155
F Blanchet
  • 1,430
  • 3
  • 21
  • 32
  • 4
    Does this answer your question? [add a string prefix to each value in a string column using Pandas](https://stackoverflow.com/questions/20025882/add-a-string-prefix-to-each-value-in-a-string-column-using-pandas) – FBruzzesi Mar 23 '20 at 11:24

1 Answers1

4

Add string with space by + and variable name:

name = 'Name'
df['protein_name'] = name + ' ' + df['protein_name']
print (df)
            protein_name  LEN  Start    End
0     Name Ribosomal_S9:  121      0    121
1     Name Ribosomal_S8:  129    121    250
2    Name Ribosomal_L10:  100    250    350
3             Name GrpE:  166    350    516
4           Name DUF150:  141    516    657
115      Name TIGR03632:  117  40149  40266
116      Name TIGR03654:  175  40266  40441
117      Name TIGR03723:  314  40441  40755
118      Name TIGR03725:  212  40755  40967
119      Name TIGR03953:  188  40967  41155

Or with f-strings:

df['protein_name'] = df['protein_name'].map(lambda x: f'{name} {x}')
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252