import pandas as pd
test = {'name': ['mnop', 'abcd', 'ijkl', 'efgh'], 'value': ['dfdf', 'jkjhk', 'cndlkcn', 'njnck']}
df = pd.DataFrame(test)
print(df)
Above code prints data as below
name value
0 mnop dfdf
1 abcd jkjhk
2 ijkl cndlkcn
3 efgh njnck
Now, I would like to sort it by name and index starting from 1 to 4 and then sequentially.
I tried, print(df.sort_values(by=['name']))
but index retains it's original association as below:
name value
1 abcd jkjhk
3 efgh njnck
2 ijkl cndlkcn
0 mnop dfdf
How can this be done?
CodePudding user response:
Your sorting point is correct and you can use the parameter ignore_index = True to have a new index
df = df.sort_values(by=['name'], ignore_index = True)
Since you then want to have an idea starting from 1 (and not 0) you have to add 1 with
df.index = 1
