jumpman8947
jumpman8947

Reputation: 581

python pandas dataframe indexing

I have a data frame

df = pd.DataFrame(carData)
df.column['models']
#df.ffill() This is where i need to fill the amount of columns i want to add with previous value

The data looks something like

          models
1         honda
2         ford
3         chevy

I want to add an index but keep it numerical up to a certain number and forward fill the models column to the last value. so for example the dataset above has 3 entries, I want to add an have a total of 5 entries it should look something like

          models
1         honda
2         ford
3         chevy
4         chevy
5         chevy

Upvotes: 1

Views: 42

Answers (2)

anky
anky

Reputation: 75150

Using df.reindex() and df.ffill()

N= 5
df.reindex(range(N)).ffill()

    models
0   honda
1   ford
2   chevy
3   chevy
4   chevy

Upvotes: 2

jezrael
jezrael

Reputation: 863611

Use reindex with method='ffill' or add ffill:

N = 5
df = df.reindex(np.arange(1, N + 1), method='ffill')
#alternative
#df = df.reindex(np.arange(1, N + 1)).ffill()
print (df)
  models
1  honda
2   ford
3  chevy
4  chevy
5  chevy

If default RangeIndex:

df = df.reset_index(drop=True)

N = 5
df = df.reindex(np.arange(N), method='ffill')
#alternative
#df = df.reindex(np.arange(N)).ffill()
print (df)
  models
0  honda
1   ford
2  chevy
3  chevy
4  chevy

Upvotes: 2

Related Questions