0

It's probably a silly thing but I can't seem to correctly convert a pandas series originally got from an excel sheet to a list.

dfCI is created by importing data from an excel sheet and looks like this:

tab      var             val
MsrData  sortfield       DetailID
MsrData  strow           4
MsrData  inputneeded     "MeasDescriptionTest", "SiteLocTest", "SavingsCalcsProvided","BiMonthlyTest"     

# get list of cols for which input is needed
cols = dfCI[((dfCI['var'] == 'inputneeded') & (dfCI['tab'] == 'MsrData'))]['val'].values.tolist()
print(cols)

>> ['"MeasDescriptionTest", "SiteLocTest", "SavingsCalcsProvided", "BiMonthlyTest"']

# replace null text with text
invalid = 'Input Needed'
for col in cols:
   dfMSR[col] = np.where((dfMSR[col].isnull()), invalid, dfMSR[col])

However the second set of (single) quotes added when I converted cols from series to list, makes all the columns a single value so that

col = '"MeasDescriptionTest", "SiteLocTest", "SavingsCalcsProvided", "BiMonthlyTest"'

The desired output for cols is

cols = ["MeasDescriptionTest", "SiteLocTest", "SavingsCalcsProvided", "BiMonthlyTest"]

What am I doing wrong?

2 Answers 2

2

Once you've got col, you can convert it to your expected output:

In [1109]: col = '"MeasDescriptionTest", "SiteLocTest", "SavingsCalcsProvided", "BiMonthlyTest"'

In [1114]: cols = [i.strip() for i in col.replace('"', '').split(',')]

In [1115]: cols
Out[1115]: ['MeasDescriptionTest', 'SiteLocTest', 'SavingsCalcsProvided', 'BiMonthlyTest']
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Mayank, this worked. However, can the single quotes be avoided so that I don't have to do this extra step? I have control on how I enter the data in excel. Currently it's entered as: "MeasDescriptionTest", "SiteLocTest", "SavingsCalcsProvided", "BiMonthlyTest"
1

Another possible solution that comes to mind given the structure of cols is:

list(eval(cols[0]))  # ['MeasDescriptionTest', 'SiteLocTest', 'SavingsCalcsProvided', 'BiMonthlyTest']

Although this is valid, it's less safe and I would go with list-comprehension as @MayankPorwal suggested.

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.