将熊猫系列带字符串转换为 python 列表

问题描述

这可能是一件愚蠢的事情,但我似乎无法正确地将最初从 Excel 工作表获得的熊猫系列转换为列表。

dfCI 是通过从 Excel 工作表导入数据创建的,如下所示:

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","BiMonthlyTest"']

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

但是,当我将 cols 从系列转换为列表时添加的第二组(单)引号使所有列成为单个值,以便

col = '"MeasDescriptionTest","BiMonthlyTest"'

cols 的期望输出

cols = ["MeasDescriptionTest","BiMonthlyTest"]

我做错了什么?

解决方法

获得 col 后,您可以将其转换为预期的输出:

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']
,

考虑到 cols 的结构,我想到的另一个可能的解决方案是:

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

虽然这是有效的,但它不太安全,我会按照@MayankPorwal 的建议使用列表理解。