The index that I have in the dataframe (with 30 rows) is of the form:
Int64Index([171, 174,173, 172, 199.............. ....175, 200])
The index is not strictly increasing because the data frame is the output of a sort(). I want to have add a column which is the series:
[1, 2, 3, 4, 5......................., 30]
How should I go about doing that?
Using the pandas. DataFrame. assign() method, you can insert multiple columns in a DataFrame, ignoring the index of a column to be added, or modify the values of existing columns. The method returns a new DataFrame object with all of the original columns as well as the additional(newly added) ones.
DataFrame - set_index() function The set_index() function is used to set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays of the correct length. The index can replace the existing index or expand on it.
You can use the assign() function to add a new column to the end of a pandas DataFrame: df = df. assign(col_name=[value1, value2, value3, ...])
How about:
df['new_col'] = range(1, len(df) + 1)
Alternatively if you want the index to be the ranks and store the original index as a column:
df = df.reset_index()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With