Gabriela M
Gabriela M

Reputation: 615

Assign column names in string to dataframe - Python

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!!!!

Upvotes: 2

Views: 1350

Answers (2)

jezrael
jezrael

Reputation: 862661

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

Upvotes: 3

U13-Forward
U13-Forward

Reputation: 71580

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

Upvotes: 1

Related Questions