For my dataset I want to replace the automatic index with the first column in the dataframe and set the new index title inline with all the column names of the dataframe.
Original dataset:
import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]]),columns=['a','b','c'])
df
a b c
0 1 2 3
1 4 5 6
Set the index as the first column:
df.set_index('a',inplace=True)
df
b c
a
1 2 3
4 5 6
However, now I am stuck on how to get the index title inline with the column headers. Below is the output I am looking for:
a b c
1 2 3
4 5 6
columns() to Convert Row to Column Header. You can use df. columns=df. iloc[0] to set the column labels by extracting the first row.
Creating a data frame from CSV file and creating row header While reading the data and storing it in a data frame, or creating a fresh data frame , column names can be specified by using the names attribute of the read_csv() method in Python.
Use this trick, but I think it is not best practice:
df.columns.name = df.index.name
df.index.name = None
print (df)
a b c
1 2 3
4 5 6
You can use
print(df.reset_index().to_string(index=False))
For example
import numpy as np
import pandas as pd
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6]]),columns=['a','b','c'])
df.set_index('a', inplace=True)
df
b c
a
1 2 3
4 5 6
print(df.reset_index().to_string(index=False))
a b c
1 2 3
4 5 6
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