hdatas
hdatas

Reputation: 1082

Create column named "Id" based on row index

I would like to create a new column for my dataframe named "Id" where the value is the row index +1. I would like to be like the example below:

   ID  Col1  ...
0  1   a     ...
1  2   b     ...
2  3   c     ...

Upvotes: 18

Views: 65563

Answers (3)

bracoo
bracoo

Reputation: 21

df['id'] = np.arange(0, len(df))

Upvotes: 1

I converted the prediction list to an array then created an dataframe with group totals and plotted the dataframe

y_pred=model.predict(X_test)

#print(y_pred)
setosa=np.array([y_pred[i][0] for i in range(len(y_pred))])
versicolor=np.array([y_pred[i][1] for i in range(len(y_pred))])
virginica=np.array([y_pred[i][2] for i in range(len(y_pred))])

df2=pd.DataFrame({'setosa': [len(setosa[setosa>.5])],'versicolor': 
[len(versicolor[versicolor>.5])], 'virginica': [len(virginica[virginica>.5])] })
df2['id']=np.arange(0,1)
df2=df2.set_index('id')
df2.plot.bar()
plt.show()

Upvotes: 1

akuiper
akuiper

Reputation: 215117

You can add one to the index and assign it to the id column:

df = pd.DataFrame({"Col1": list("abc")})

df["id"] = df.index + 1

df
#Col1   id
#0  a    1
#1  b    2
#2  c    3

Upvotes: 35

Related Questions