1

I have a pandas dataframe like this

import pandas as pd

data = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
        'year': [2012, 2012, 2013, 2014, 2014],
        'reports': [4, 24, 31, 2, 3]}

DF = pd.DataFrame(data)

I need to add a new column named "key" to be filled with new values, to produce a new dataframe like this

data2 = {'name': ['Jason', 'Molly', 'Tina', 'Jake', 'Amy'],
        'year': [2012, 2012, 2013, 2014, 2014],
        'reports': [4, 24, 31, 2, 3],
        'keys': ["p1s4", "p1s24", "p1s31", "p1s2", "p1s3"]}

DF2 = pd.DataFrame(data2)

I wrote a code like this

DF["key"] = "p" + str(1) + "s" + str(DF["reports"]) 

But it doesn't work

ilFonta
  • 271
  • 3
  • 18

1 Answers1

1

You were almost there, you need to use a vectorial method (astype) to convert to string:

DF["key"] = "p" + str(1) + "s" + DF["reports"].astype(str)

Assuming the number is a variable, note that you can even simplify to:

x = 1
DF["key"] = f"p{x}s" + DF["reports"].astype(str)

Output:

    name  year  reports    key
0  Jason  2012        4   p1s4
1  Molly  2012       24  p1s24
2   Tina  2013       31  p1s31
3   Jake  2014        2   p1s2
4    Amy  2014        3   p1s3
mozway
  • 194,879
  • 13
  • 39
  • 75