python - 如何迭代字符串的DataFrame并在结果上应用条件
问题描述
我正在尝试使用 if 条件迭代数据帧以返回一个值,如果字符串等于数据帧中第 i 个位置的字符串。
我通过运行示例代码得到以下错误
(`ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().`):
df = {'step_ID':[1,1,2,2,3,3,4,4], 'step_name':['CC_Dchg', 'CC_Dchg', 'Rest', 'Rest', 'CC_Chg',
'CC_Chg', 'Rest', 'Rest']}
df = pd.DataFrame(df)
chg_step = []
a = []
for i in df:
if df['step_name'] == 'CC_Chg':
a = SiO_1['step_ID']
chg_step = chg_step + a
else:
continue
检查是否df['step_name'] == 'CC_Chg'
为真的正确语法是什么?
解决方案
如果我理解正确,您需要等于给定值step_ID
的行数。step_name
在 pandas 中,您不必编写自己的循环(或仅在极端情况下)。相反,这里有一个替代方案:
# step by step
# do the comparison step_name == X for each row.
# The result is a boolean pandas Series
mask = df['step_name'] == 'CC_Chg'
# The boolean pandas series can be used to select only some rows.
# Then, we can retrieve the step_ID column for those rows only.
# The result is again a pandas Series
chg_step_series = df[mask].step_ID # this is a series
# A pandas series can be converted to a numpy array using values,
# and then a list by calling tolist()
chg_step_series.values.tolist() # this is a list: [3,3]
或者,在一行中:
chg_step = df[df.step_name == 'CC_Chg'].step_ID.values.tolist()
推荐阅读
- javascript - Javascript 计数器变为 0 而不是给定的数字
- javascript - 我可以使用 JavaScript 获取电话联系人列表吗?
- java - 滚动后Android Gridview不保持选择
- c++ - 在 C++ 中将类(带有 Vector 成员)保存为二进制文件
- java - 如何将框架布局的 y 值设置为屏幕高度的 3/4?
- python - MIDI:具有相同数据的多个 Program Change Event
- java - 为什么实体对象在方法返回后会被分离?(弹簧数据JPA)
- c# - 在c#中对浮点数数组进行排序
- mysql - 在一张表上插入后,取决于数量取决于另一张表中有多少条目 - MySQL 触发器
- amazon-web-services - 使用 Terraform v 0.11.10 的 AWS ECS 容量提供程序