我有一个 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
如何对一系列列表使用应用/转换?
答案 0 :(得分:3)
只需使用 apply()
方法:-
df['values'].apply(lambda x:x.append('d'))
现在,如果您打印 df
,您将获得所需的输出:-
values
0 [a, b, d]
1 [c, d]
2 [b, c, d]
答案 1 :(得分:1)
问题是需要处理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'])
Better 被称为 DataFrame
df
然后使用:
df['values'].apply(lambda x: x + ['d'])