2

I have the following string in Python (is not a list, is a string):

a = ['cc_call_center_sk', 'cc_call_center_id', 'cc_rec_start_date', 'cc_rec_end_date']

I also have the following dataframe:

   0      1      2      3
0  AA     AB     BC     CD
1  AZ     ZR     RT     TN

What I want to do is to assign the string 'a' to the columns of the dataframe. I did this:

df.columns = a

But I get the following error:

TypeError: Index(...) must be called with a collection of some kind, 
"['cc_call_center_sk', 'cc_call_center_id', 'cc_rec_start_date', 
'cc_rec_end_date']" was passed

I cannot pass directly the string to the df.columns. Any ideas on this? Thanks!!!!

2 Answers 2

3

You need convert strings to list by ast.literal_eval:

import ast

df.columns = ast.literal_eval(a)

Another solution with strip and split, last remove ' for each column name:

a = "['cc_call_center_sk', 'cc_call_center_id', 'cc_rec_start_date', 'cc_rec_end_date']"

#solution 1
df.columns = [x.strip("'") for x in a.strip("[]").split(', ')]
#solution 2
df.columns = pd.Index(a.strip('[]').split(', ')).str.strip("'")

print (df)
  cc_call_center_sk cc_call_center_id cc_rec_start_date cc_rec_end_date
0                AA                AB                BC              CD
1                AZ                ZR                RT              TN
Sign up to request clarification or add additional context in comments.

3 Comments

Amazing! Thanks @jezrael
@GabrielaMartinez - You are welcome! I notice first my answer was accepted and then remove accepting, so only ask if it was by accident or not - now is possible accept only one answer, not multiple. And which answer you choose it is up to you ;)
Sorry about that! :)
1

Or even better, use split:

df.columns = map(lambda x:x[1:-1],a[1:-1].split(', '))

Then now:

print(df)

Will be desired output, like:

  cc_call_center_sk cc_call_center_id cc_rec_start_date cc_rec_end_date
0                AA                AB                BC              CD
1                AZ                ZR                RT              TN

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.