用包含单个字符串的列表替换 pandas 系列的元素

Replace elements of a pandas series with a list containing a single string

我正在尝试用包含单个字符串的列表替换 pandas 系列中的空列表。这是我拥有的:

a = pd.Series([ 
    [],
    [],
    ['a'],
    ['a'],
    ["a","b"]
])

期望的输出如下:

b = pd.Series([ 
    ['INCOMPLETE'],
    ['INCOMPLETE'],
    ['1'],
    ['1'],
    ["1","2"]
])

在我尝试使用布尔索引替换空列表的地方,我将我的唯一字符串列表自动强制转换为字符串字符串:

a[a.map(len) == 0 ] = ['INCOMPLETE']
0    INCOMPLETE
1    INCOMPLETE
2           [a]
3           [a]
4        [a, b]

相比之下,手动替换工作 a[0] = ['INCOMPLETE']

有人有解决方法吗?

您无法在 pandas 中轻松分配列表(pandas 无法将列表作为项目使用),您需要在此处循环:

b = pd.Series([x if x else ['INCOMPLETE'] for x in a], index=a.index)

输出:

0    [INCOMPLETE]
1    [INCOMPLETE]
2             [a]
3             [a]
4          [a, b]
dtype: object

使用带有 if-else 的 lambda 函数来替换空字符串,因为如果 comapre 正在处理 False:

a = a.apply(lambda x: x if x else ['INCOMPLETE'])
print (a)
0    [INCOMPLETE]
1    [INCOMPLETE]
2             [a]
3             [a]
4          [a, b]
dtype: object
import pandas as pd

a = pd.Series([ 
    [],
    [],
    ['a'],
    ['a'],
    ["a","b"]
])

convert_num = lambda x:list(map(lambda y:ord(y)-ord('a')+1,x))
map_data = lambda x:'Incomplete' if x==[] else convert_num(x) 
a = a.apply(map_data)
0    Incomplete
1    Incomplete
2           [1]
3           [1]
4        [1, 2]
dtype: object