Python pandas.DataFrame How to Adjust Column Order and Modify index Name
- 2021-06-29 11:40:13
- OfStack
1. Create DataFrame from a dictionary
>>> import pandas
>>> dict_a = {'user_id':['webbang','webbang','webbang'],'book_id':['3713327','4074636','26873486'],'rating':['4','4','4'],'mark_date':['2017-03-07','2017-03-07','2017-03-07']}
>>> df = pandas.DataFrame(dict_a) # Create from Dictionary DataFrame
>>> df # Created df Column names are sorted alphabetically by default, not in dictionary order 1 Yes, in the dictionary 'user_id','book_id','rating','mark_date'
book_id mark_date rating user_id
0 3713327 2017-03-07 4 webbang
1 4074636 2017-03-07 4 webbang
2 26873486 2017-03-07 4 webbang
2. Adjust column order
>>> df = df[['user_id','book_id','rating','mark_date']] # Adjust column order to 'user_id','book_id','rating','mark_date'
>>> df
user_id book_id rating mark_date
0 webbang 3713327 4 2017-03-07
1 webbang 4074636 4 2017-03-07
2 webbang 26873486 4 2017-03-07
3. Adjust index to start from 1
>>> df.index = range(1,len(df) + 1) # take index Change from 1 start
>>> df
user_id book_id rating mark_date
1 webbang 3713327 4 2017-03-07
2 webbang 4074636 4 2017-03-07
3 webbang 26873486 4 2017-03-07
Summary of DataFrame operations: https://www.ofstack.com/article/163645.htm