如何使用pandas python将unicode字符串转换为列表?

时间:2016-05-03 10:02:18

标签: python python-2.7 pandas

我有一个像[u'1,2,3,4']这样的unicode字符串,我希望将其转换为[1,2,3,4]

示例:

a=[u'1,2,3']

我从url值得到这个,我必须将此格式转换为:

a= [1,2,3]

可以比较这个列表值是否存在于pandas数据帧的特定列中?

1 个答案:

答案 0 :(得分:2)

如何测试您的DataFrame是否包含值

假设你有数组[1, 2, 3],这里有关于如何测试DataFrame是否包含值的方法

>>> df = pd.DataFrame({'a': [1, 3, 5, 7, 9]})
>>> a = [1, 2, 3]
>>> for x in a:
...     print '{x} is in df'.format(x=x), any(df.a == x)
... 
1 is in df True
2 is in df False
3 is in df True

我使用df.<column_name> == <test_value>并将其包装在any()中,如果找到至少一个匹配则返回true

如何获取数组

我将字符串拆分为,,然后将结果转换为int

>>> [int(x) for x in [u'1,2,3'][0].split(',')]
[1, 2, 3]

解释

>>> a=[u'1,2,3'] 
>>> a
[u'1,2,3']          # This a list with one string: '1,2,3'
>>> a = a[0]
>>> a
u'1,2,3'            # I get the string from the list above
>>> a.split(',')    # I split this string on ','
[u'1', u'2', u'3']  # this is still a list of strings, 
                    # so I run int(x) on each element
                    # using a list comprehension below

>>> [int(x) for x in [u'1,2,3'][0].split(',')]
[1, 2, 3]           # the result you want