gpt4 book ai didi

python - ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。 df[条件]

转载 作者:行者123 更新时间:2023-12-05 03:30:33 33 4
gpt4 key购买 nike

如果“embark_town”列中的数据是“Southampton”,我想将它们全部更改为“manchester”。因此,在使用条件设置访问数据后,我应用了“应用”功能。有什么问题?

# Import Packages
import pandas as pd
import numpy as np
import seaborn as sns

# dataset upload
df = sns.load_dataset("titanic")
df = df.rename(columns={'pclass':'passenger_class','sex':'gender','age':'old'})

def change(name):
if name == 'Southampton':
name = 'Manchester'
return name

condition = (df.embark_town == 'Southampton')

df[condition] = df[condition].apply(change)
df

获取错误:

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-2cf6d75dce9e> in <module>()
14
15 condition = (df.embark_town == 'Southampton')
---> 16 df[condition] = df[condition].apply(change)
17 df
18 # df['embark_town'] = df['embark_town'].apply(change)

5 frames
/usr/local/lib/python3.7/dist-packages/pandas/core/generic.py in __nonzero__(self)
1328 def __nonzero__(self):
1329 raise ValueError(
-> 1330 f"The truth value of a {type(self).__name__} is ambiguous. "
1331 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
1332 )

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

最佳答案

正如 Michael Szczesny 在评论中也指出的那样。 DataFrame.apply 使用 Series 作为输入。定义的 change(name) 函数需要一个字符串。消息 ValueError: The truth value of a Series is ambiguous.使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。 来自尝试将 Series 与字符串进行比较.

Register Sole 指出的一个解决方法是改用条件。

condition = (df[‘embark_town’] == 'Southampton')
df[condition]['embark_town'] = 'Manchester'

要继续使用 apply,更改函数需要看起来像这样:

def change(series):
if series.name == 'embark_town':
series[series.values == 'Southampton'] = 'Manchester'

return series

关于python - ValueError : The truth value of a Series is ambiguous. 使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。 df[条件],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70809477/

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