Pandas: 如何对一系列列表使用 apply

Pandas: how to use apply with a series of lists

我有一个 Pandas 系列列表:

| id | values         |
| -- | -------------- |
| 0  | ['a', 'b']     |
| 1  | ['c']          |
| 2  | ['b', 'c']     |

我想对每个列表应用一个函数。

让我们使用一个非常简单的函数,将 'd' 添加到每个列表,并将其应用于系列:

def append_d(x):
    print(x)
    return x + ['d']
my_series.apply(append_d)

这会导致错误:

Cannot broadcast np.ndarray with operand of type <class 'list'>

我尝试了以下方法:

my_series.apply(lambda x: x + ['d']) # same error as above
my_series.transform(append_d) # ValueError: Transform function failed
my_series.transform(lambda x: x + ['d']) # ValueError: Transform function failed

如何将 apply/transform 用于一系列列表?

只需使用apply()方法:-

df['values'].apply(lambda x:x.append('d'))

现在,如果您打印 df,您将获得所需的输出:-

    values
0   [a, b, d]
1   [c, d]
2   [b, c, d]

问题需要处理 Series,这意味着列 values 而不是 DataFrame 调用了 series:

print (type(series))
<class 'pandas.core.frame.DataFrame'>

print (type(series['values']))
<class 'pandas.core.series.Series'>

series['values'].apply(lambda x: x + ['d'])

更好的是调用DataFrame df然后使用:

df['values'].apply(lambda x: x + ['d'])