Let's say I have this dataframe:
Name Salary Field
0 Megan 30000 Botany
1 Ann 24000 Psychology
2 John 24000 Police
3 Mary 45000 Genetics
4 Jay 60000 Data Science
I want to add some 0-indexed numbers above the column names, but I'd also want to keep the column names. I want to reach this form:
0 1 2
Name Salary Field
0 Megan 30000 Botany
1 Ann 24000 Psychology
2 John 24000 Police
3 Mary 45000 Genetics
4 Jay 60000 Data Science
How can I do that with pandas and Python?
You don't need to create a new dataframe:
df.columns = pd.MultiIndex.from_tuples(list(enumerate(df)))
As expected:
# 0 1 2
# Name Salary Field
# 0 Megan 30000 Botany
# 1 Ann 24000 Psychology
# 2 John 24000 Police
# 3 Mary 45000 Genetics
# 4 Jay 60000 Data Science
I hope this helps.
Here is a quick way
new_df = pd.DataFrame(df.values,
columns = [ list(range(df.shape[1])), df.columns]
)
I'm sure there is a more elegant way
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.