0

There are 2 dataframes

df1 and df2

df1 =

A   B
111 222
222 5555

df2 =

C   counter_2
333 100
777 25

I need to add a column "counter" to df1, it should just be like index, return the position of column's elements.

Like this:

df1['counter'] = range(len(df1))

A   B   counter
111 222       1
222 555       2

But I need to change the starting point, it should be the max number from df2 "counter" column.

df2['counter_2'].max() # 100

So my desired output is like:

A   B   counter
111 222       101
222 555       102

I've googled, but I can't find a solution.

Anna
  • 914
  • 9
  • 25

3 Answers3

1
import numpy as np
df1['counter'] = np.arange(df2['counter_2'].max(), len(df1) + 1)
CY_
  • 7,170
  • 1
  • 15
  • 26
  • You can also look at this answer for more detail: https://stackoverflow.com/questions/32249960/in-python-pandas-start-row-index-from-1-instead-of-zero-without-creating-additi/32249984 – CY_ Oct 01 '19 at 08:31
1
# First, compute the starting point
start_point = df2['counter_2'].max() + 1

# Now, assign a range of numbers to the 'counter' column of df1
df1['counter'] = list(range(start_point, start_point + len(df1)))
Marijn van Vliet
  • 5,239
  • 2
  • 33
  • 45
1

when we create dataframe it has a default index which you are not showing above.if you have set another column as index then you would have to reset it and then add new column containing sum of max of counter2 and index like so:

 max_value = df2['counter_2'].max()     
 df1 = df1.reset_index()
 df1['counter'] = df1.index+max_value
 print(df1.head())

also use meaningful names for columns and dataframe. Thanks.

Atlas Bravoos
  • 360
  • 2
  • 12