gpt4 book ai didi

python - Pandas:如何将 apply 与一系列列表一起使用

转载 作者:行者123 更新时间:2023-12-04 12:15:50 25 4
gpt4 key购买 nike

我有一个 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()方法:-

df['values'].apply(lambda x:x.append('d'))
现在,如果您打印 df你会得到你想要的输出:-
    values
0 [a, b, d]
1 [c, d]
2 [b, c, d]

关于python - Pandas:如何将 apply 与一系列列表一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66672980/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com