2

I have dataframe with these columns:

grpby_sum_df.head()
Out[82]: 
   BusNumber PNode  participationFactor  normalized Contained by  \
0     242514  HQST                  1.0    0.000471         HQST   
1     242514  ISNE                  1.0    0.000471         ISNE   
2     242514  NBSO                  1.0    0.000471         NBSO   
3     242514  NSSO                  1.0    0.000471         NSSO   
4     242514  NYIS                  1.0    0.000471         NYIS   

  Initial Value    ParFac AutoCalc?  
0     SPECIFIED  0.000471        NO  
1     SPECIFIED  0.000471        NO  
2     SPECIFIED  0.000471        NO  
3     SPECIFIED  0.000471        NO  
4     SPECIFIED  0.000471        NO

I need to create another column called Object with word gen followed by the bus number column in the middle and wrapped by single quotes and number 99 also wrapped by single quotes.

Gen 'BusNumber' '99'

Please advise.

Alex
  • 6,610
  • 3
  • 20
  • 38
Shyama Sonti
  • 321
  • 1
  • 5
  • 16
  • 1
    You would probably get better answers and exposure if you add the `python` tag to your question. – Abion47 Aug 08 '18 at 17:56

3 Answers3

0

This will add the column as you've given in your question i.e with spaces separating Gen 'BusNumber' '99' complete with the quotes

df['Object'] = "Gen '" + df['BusNumber'].astype('str') + "' '99'"
Alex
  • 6,610
  • 3
  • 20
  • 38
0

You simply need:

df['object'] = "Gen " + df.BusNumber.map(str) + " 99"

Output (Omitting some columns that are irrelevant):

   BusNumber         object
0     242514  Gen 242514 99
1     242514  Gen 242514 99
2     242514  Gen 242514 99
3     242514  Gen 242514 99
4     242514  Gen 242514 99
harvpan
  • 8,571
  • 2
  • 18
  • 36
  • Had to modify slightly to my need but your answer got be going. df['Object'] = "Gen '" + df['BusNumber'].astype('str') + "' '99'". Did not realize that double quote can be used to wrap single quote. So hard to find this answer in the forum. – Shyama Sonti Aug 08 '18 at 18:12
0

String operations are sometimes very slow in pandas, and you can actually get better performance with list comprehensions (if performance is relevant).

You could do it with f strings if you are using Python 3.6+, and using the escape character (\) to include your single quotes:

df['Object'] = [f'Gen \'{i}\' \'99\'' for i in df.BusNumber]

If using an older version of python, you can use .format():

df['Object'] = ['Gen \'{}\' \'99\''.format(i) for i in df.BusNumber]

Or:

df['Object'] = ['Gen \'%s\' \'99\'' %i for i in df.BusNumber]
sacuL
  • 49,704
  • 8
  • 81
  • 106