gpt4 book ai didi

python - 根据 pandas 列中的数据,当 true 为 1 和 0 时附加一个空列表?

转载 作者:行者123 更新时间:2023-12-01 01:49:55 36 4
gpt4 key购买 nike

import pandas as pd
from pandas import DataFrame,Series
import numpy as np
titanic=pd.read_csv('C:/Users/prasun.j/Downloads/train.csv')
sex=[]
if titanic['Sex']=='male':
sex.append(1)
else:
sex.append(0)
sex

我正在尝试创建一个列表,当 if 语句遇到男性时应追加 1 或遇到女性时应追加 0,我不知道我做错了什么,有人可以帮忙吗,提前感谢,执行抛出以下错误

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-6-265768ba34be> in <module>()
4 titanic=pd.read_csv('C:/Users/prasun.j/Downloads/train.csv')
5 sex=[]
----> 6 if titanic['Sex']=='male':
7 sex.append(1)
8 else:

C:\anaconda\lib\site-packages\pandas\core\generic.pyc in __nonzero__(self)
1119 raise ValueError("The truth value of a {0} is ambiguous. "
1120 "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1121 .format(self.__class__.__name__))
1122
1123 __bool__ = __nonzero__

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

最佳答案

当您检查if titanic['Sex']=='male'时,您正在将male与整个系列进行比较,其中这就是您收到 ValueError 的原因。

如果您确实想继续使用迭代方法,您可以使用iterrows,并检查每行的条件。但是,您应该避免使用 Pandas 进行迭代,这里有一个更简洁的解决方案。

设置

df = pd.DataFrame({'sex': ['male', 'female', 'male', 'male', 'female']})

只需在此处使用np.where:

np.where(df.sex == 'male', 1, 0)
# array([1, 0, 1, 1, 0])

您还可以使用 bool 索引:

(df.sex == 'male').astype(int).values.tolist()
# [1, 0, 1, 1, 0]

关于python - 根据 pandas 列中的数据,当 true 为 1 和 0 时附加一个空列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50828595/

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