'Can I name 2 subsequent columns identical like the previous one? (python)
I have a dataset in Excel and some columns are unnamed there: A_ColumnWithName, Unnamed1, Unnamed2, B_ColumnWithName, Unnamed3, Unnamed4
I need to set the names of the currently unnamed columns to the same as the 1st column name from the left, so my columns should look like this:
A_ColumnWithName, A_ColumnWithName, A_ColumnWithName, B_ColumnWithName, B_ColumnWithName, B_ColumnWithName
Any hints how can I do it using Python? An important thing is that there is tons of such columns that's why it's required to do so in the most automatic way possible.
Solution 1:[1]
The following code would work.
import pandas as pd
df = pd.DataFrame( columns= ["A_ColumnWithName", "unnamed","unnamed", "B_ColumnWithName", "unnamed", "unnamed"])
replaceWith = df.columns.values[0]
for i in range(1, len(df.columns)):
if df.columns[i] == 'unnamed':
df.columns.values[i] = replaceWith
else:
replaceWith = df.columns.values[i]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
