![]() |
How replace Unnamed header column with previous - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Data Science (https://python-forum.io/forum-44.html) +--- Thread: How replace Unnamed header column with previous (/thread-20501.html) |
How replace Unnamed header column with previous - SriMekala - Aug-14-2019 Hi, I have excel file with merged columns as below: Category Group Sub_valid Name Item Value Color Status Group1 VGT Power 0 VGT Power BHA Voltage 1 BHA VoltageGroup is merged for Name & Item column, Sub_valid is a merged column for Value, Color, Status. When I read using: import pandas as pd df = pd.read_excel('D:PythonCodes\mergedinput.xlsx',sheetname='Sheet1')The column above Item is "Unnamed0" & Color column & Status column are "Unnamed1", Unnamed2", But I want: Category Group Group Sub_valid Sub_valid Sub_valid Name Item Value Color Status Group1 VGT Power 0 VGT Power BHA Voltage 1 BHA VoltageI use below code but it needs to do multiple time: df.rename(columns={'*Unnamed: 1':'nan'}, inplace=True)but I want to replace if header starts with: Unnamed" RE: How replace Unnamed header column with previous - boring_accountant - Aug-14-2019 Assuming you want to replace all columns containing the string 'Unnamed' with the string 'nan', this will do: print(df) df.columns = [col if not 'Unnamed' in col else 'nan' for col in df.columns] print(df) As an alternative, the following yields equal results. I'm not sure whichever I prefer but both are possible.df.columns = df.columns.map(lambda col: col if not 'Unnamed' in col else 'nan') RE: How replace Unnamed header column with previous - SriMekala - Aug-15-2019 Category Group Group Sub_valid Sub_valid Sub_valid Name Item Value Color Status Group1 VGT Power 0 VGT Power BHA Voltage 1 BHA VoltageBut I want to "Unnamed column should replace with previous not "Unnamed column" like, above RE: How replace Unnamed header column with previous - boring_accountant - Aug-15-2019 The following function should do the trick. This won't win any beauty prize however as I just quickly hacked this together. def repeat_cols(columns): last_non_unnamed = '' if 'unnamed' in columns[0].lower() else columns[0] new_columns = [] new_column = '' for column in columns: if 'unnamed' in column.lower(): new_column = last_non_unnamed else: new_column = column last_non_unnamed = new_column new_columns.append(new_column) return new_columns df.columns = repeat_cols(df.columns) |