1

I am trying to add an incrementing number to the end of a string and apply this to every row in one column of my dataframe. The column has 76 rows. Ideally I want the output to look like this:

Event Reference Number
FEBRUARY_2019_1
FEBRUARY_2019_2
FEBRUARY_2019_3

I am trying to use apply with a lambda function but am stuck trying to figure out the next step.

df_Trade_File['Event Reference Number'].apply(lambda x: enumerate(df_Trade_File['Event Reference Number']))

2 Answers 2

2

First thing to note is that for the change to take affect you will need to set your df to the result at which time you could use apply or something to format it but in this situation you could probably do something simpler like:

df_Trade_File['Event Reference Number'] = df_Trade_File['Event Reference Number'] + '_' + str(df.index)

assuming you are using a standard index of 1-76.

Sign up to request clarification or add additional context in comments.

2 Comments

Nice answer, I hope you don't mind but I stole your df.index idea. It makes the line shorter and cleaner assuming generic index ofc
This is what gets returned in each row when I use that: "FEBRUARY_2019__Int64Index([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75], dtype='int64')"
1

Try using Series.str.cat

df["Event Reference Number"] = df["Event Reference Number"].str.cat(map(str, df.index), sep='_')

If you're using an index other than standard index replace map(str, df.index) with a range but make it all strings or python will yell at you:

map(str, range(1, df.shape[0]+1))

1 Comment

I get a raise ValueError when I use this: raise ValueError("Did you mean to supply a sep keyword?")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.