Turn the column headers into the first row and row headers into the first column in Pandas dataframe
for your solution, you can just shift it. But if you are reading the data from any csv file, while reading you can take considerations of not taking header(header = None)
345 456 789
123
987 876 765 543
df.reset_index().T.reset_index().T
Out:
0 1 2 3
index 123 345 456 789
0 987 876 765 543
pd.read_csv('data.csv',header=None)
Out:
0 1 2 3
0 123 345 456 789
1 987 876 765 543
How to set column headers to the first row in Pandas dataframe?
You can use np.vstack
on a list of column names and the DataFrame to create an array with one extra row; then cast it into pd.DataFrame
:
out = pd.DataFrame(np.vstack([df.columns, df]))
Output:
0 1 2
0 A B C
1 1 2 3
2 4 5 6
3 7 8 9
move column names to first row in pandas frame
One line DataFrame.T
+ DataFrame.reset_index()
. You can set the names of columns with DataFrame.set_axis()
new_df = (df.T.reset_index().T.reset_index(drop=True)
.set_axis([f'Q1.{i+1}' for i in range(df.shape[1])], axis=1))
print(new_df)
Output
Q1.1 Q1.2 Q1.3 Q1.4 Q1.5
0 a b c d e
1 1 2 2 2 2
2 2 3 3 3 3
3 3 4 4 4 4
4 4 5 5 5 5
5 5 6 6 6 6
6 6 7 7 7 7
Python Pandas Replacing Header with Top Row
new_header = df.iloc[0] #grab the first row for the header
df = df[1:] #take the data less the header row
df.columns = new_header #set the header row as the df header
Convert row to column header for Pandas DataFrame,
In [21]: df = pd.DataFrame([(1,2,3), ('foo','bar','baz'), (4,5,6)])
In [22]: df
Out[22]:
0 1 2
0 1 2 3
1 foo bar baz
2 4 5 6
Set the column labels to equal the values in the 2nd row (index location 1):
In [23]: df.columns = df.iloc[1]
If the index has unique labels, you can drop the 2nd row using:
In [24]: df.drop(df.index[1])
Out[24]:
1 foo bar baz
0 1 2 3
2 4 5 6
If the index is not unique, you could use:
In [133]: df.iloc[pd.RangeIndex(len(df)).drop(1)]
Out[133]:
1 foo bar baz
0 1 2 3
2 4 5 6
Using df.drop(df.index[1])
removes all rows with the same label as the second row. Because non-unique indexes can lead to stumbling blocks (or potential bugs) like this, it's often better to take care that the index is unique (even though Pandas does not require it).
Python: How do I 'demote' a column header to be a row and rename column headers (without replacing the original column headers)?
As mentioned in the comment, if you are reading CSV
file, you can pass the column names:
df = pd.read_csv(filePath, names=["Faculty", "Male", "Female", "Total"])
But if you already have the dataframe, you can add the columns to index at -1, then you can reset the index, you can also sort the index if needed.:
df.loc[-1] = df.columns.to_list()
df = df.sort_index().reset_index(drop=True)
df.columns = ['Faculty', 'Male', 'Female', 'Totals']
Turn column headers into the first row of my df
I think you need header=None
:
pd.read_html(route, flavor='html5lib',header=None)
Merge the first row with the column headers in a dataframe
I think you need numpy.concatenate
, similar principe like cᴏʟᴅsᴘᴇᴇᴅ answer:
df.columns = np.concatenate([df.iloc[0, :2], df.columns[2:]])
df = df.iloc[1:].reset_index(drop=True)
print (df)
Sample type Concentration A B C D E F \
0 Water 9200 95.5 21.0 6.0 11.942308 64.134615 21.498560
1 Water 9200 94.5 17.0 5.0 5.484615 63.205769 19.658560
2 Water 9200 92.0 16.0 3.0 11.057692 62.586538 19.813120
3 Water 4600 53.0 7.5 2.5 3.538462 35.163462 6.876207
G H
0 5.567840 1.174135
1 4.968000 1.883444
2 5.192480 0.564835
3 1.641724 0.144654
First row to header with pandas
what about defining that when you load your table in the first place?
pd.read_csv('filename', header = 1)
otherwise I guess you can just do this:
df.drop('0', axis = 1)
Related Topics
How to Dynamically Build a Json Object
Splitting Dictionary Items into Smaller Dictionaries Based on Condition
How to Print Superscript in Python
How to Avoid Last Comma in Python Loop
Suppress Stdout/Stderr Print from Python Functions
Jsondecodeerror: Expecting Value: Line 1 Column 1 (Char 0)
Sum Numbers of Each Row of a Matrix Python
How to Create Dynamic Workflows in Airflow
How to Get the Url of the Active Google Chrome Tab in Windows
How to Run an .Ipynb Jupyter Notebook from Terminal
How to Write Multiple Images (Subplots) into One Image
Making a Discord Bot Change Playing Status Every 10 Seconds
How to Get the Name of an Object
Cv2 Image Error: Error: (-215:Assertion Failed) !Ssize.Empty() in Function 'Cv::Resize'
Python: Printing Horizontally Rather Than Current Default Printing
How to Replace Nan Values Where the Other Columns Meet a Certain Criteria
Python: Split a List into Multiple Lists Based on a Subset of Elements