1

I am currently trying to change the following column names:

Unnamed: 1 | Unnamed: 2         <----- Column names
    Alfa       Beta             <----- Data 

Into:

 2016 | 2017
 Alfa   Beta

I have used:

df.rename(columns=lambda x: re.sub(r"Unnamed\:\s\d+"," ",x))

To replace the column names with a blank space, but I want to create a loop so automatically can be replaced into 2016 and 2017

[Additionally] I made this to create the list of values

for i in range(len(df.columns[:])):
    i+=2016
    str(i)

Result gives:

2016
2017

Is there any method in which I can substitute those values into the list comprehension?

2
  • Does this answer help? stackoverflow.com/a/40454054/42346 Commented May 4, 2020 at 4:52
  • i assume u get these headers when u read in the data. you could set the column names directly when doing so Commented May 4, 2020 at 4:54

3 Answers 3

5
df.rename(columns=lambda x: int(x.strip('Unnamed: '))+2015)
Sign up to request clarification or add additional context in comments.

Comments

2

I think list comprehension here is not necessary, only assign range with start from variable:

start = 2016
df.columns = range(start, start + len(df.columns))
print (df)
   2016  2017
0  Alfa  Beta

Comments

0

Stumped into this, to do what OP asked with list comprehension:

df.columns = [re.sub(r'Unnamed: [12]', lambda x: str(int(x.group(0).strip('Unnamed: '))+2015), item) for item in df.columns]

I know this is a a really long one-liner but OP asked for it, but agree with others, do it manually is the way to go unless the df is huge with a lot of columns. The lambda function portion should be a stand alone function which will allow much more flexibility for more advanced manipulation.

this one line can change below header:

    col1    Unnamed: 1  col3    Unnamed: 2
0    1        Alfa        3       Beta

to:

  col1  2016    col3    2017
0   1   Alfa     3      Beta

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.