Home > Back-end >  Python-Pandas: Continue row value increment with adding a different database
Python-Pandas: Continue row value increment with adding a different database

Time:08-27

So I have a df that goes like this df1:

10AE City
1427 New York
1428 Los Angeles
1429 Karachi
1430 London
1431 Barcelona
1432 Madrid

Now i have another database that has a similar columns but different citys df2:

10AE City
1 New Orleans
2 San Francisco
3 Manchester
4 Toronto
5 Atlanta
6 Lahore

I want to append the second database into the first one but continue the incrementing row values from the first one like this:

10AE City
1427 New York
1428 Los Angeles
1429 Karachi
1430 London
1431 Barcelona
1432 Madrid
1433 New Orleans
1434 San Francisco
1435 Manchester
1436 Toronto
1437 Atlanta
1438 Lahore

Does anyone have any idea how to do this? Any help would be appreciated!!

Thank you so much!!

CodePudding user response:

If you want a simple hack you can do

df2['10AE'] = 1
df2.iloc[0,0] = df1.iloc[-1,0]   1
df2['10AE'] = df2['10AE'].cumsum()

After that you can concat the dfs

but there's probably more efficient ways to do this.

CodePudding user response:

Just add the max of df1's 10AE column to df2's 10AE column. Then concat them together.

df2['10AE']  = 1432

df = pd.concat([df1, df2], ignore_index=True)
print(df)

# Output:

    10AE           City
0   1427       New York
1   1428    Los Angeles
2   1429        Karachi
3   1430         London
4   1431      Barcelona
5   1432         Madrid
6   1433    New Orleans
7   1434  San Francisco
8   1435     Manchester
9   1436        Toronto
10  1437        Atlanta
11  1438          Lahor

CodePudding user response:

So I figured out if anyone wants help with this! This works for me but other answers are also very helpful!!

last_row = int(df1['10AE'].tail(1)) 1
df2['10AE'] = range(last_row, last_row len(df2))

and then you can concat df2 Thank you so much for all your help!

  • Related