Pandas get max ID in rows and add to empty rows

Viewed 161

I'm trying to automatically add ID# to every row in a pandas dataframe.

example:

   ID Ticker
0   0   AAPL
1   0   TSLA
2   0   GOOG

The 'ID' column should automatically be filled in like this:

output:

   ID Ticker
0   1   AAPL
1   2   TSLA
2   3   GOOG

I am having issues achieving this though. I tried multiple things, including making a function to iterate over every row, but so far I am having issues with this seemingly simple task. I was hoping someone on here could help me out to achieve this.

sample code:

import pandas as pd

df1 = pd.DataFrame({'ID': [0, 0, 0],
                'Ticker': ['AAPL', 'TSLA', 'GOOG']})
print(df1)

output = pd.DataFrame({'ID': [1, 2, 3],
                'Ticker': ['AAPL', 'TSLA', 'GOOG']})

print(output)

Thanks!

3 Answers

Try this,

df['ID'] = df.index + 1

By doing this, the value of index + 1 is added in ID column, if your index is correctly in order

This will give each ticker a unique numeric id

df1['ID'] = df1['Ticker'].astype('category').cat.codes
import pandas as pd

df1 = pd.DataFrame({'ID': [0, 0, 0],
                'Ticker': ['AAPL', 'TSLA', 'GOOG']})

df1.ID = [x for x in range(1, len(df1.values)+1)]

print(df1)
   ID Ticker
0   1   AAPL
1   2   TSLA
2   3   GOOG

Related