gpt4 book ai didi

python - 数据帧上的条件迭代

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:19 25 4
gpt4 key购买 nike

我有一个数据框df,看起来像:

    id              location    grain
0 BBG.XETR.AD.S XETR 16.545
1 BBG.XLON.VB.S XLON 6.2154
2 BBG.XLON.HF.S XLON NaN
3 BBG.XLON.RE.S XLON NaN
4 BBG.XLON.LL.S XLON NaN
5 BBG.XLON.AN.S XLON 3.215
6 BBG.XLON.TR.S XLON NaN
7 BBG.XLON.VO.S XLON NaN

实际上这个数据框会大得多。我想迭代这个返回 'grain' 值的数据帧,但我只对“grain”列中具有值(而不是 NaN)的行感兴趣。因此,当我迭代数据帧时仅返回以下值:

16.545
6.2154
3.215

我可以使用以下方法迭代数据帧:

for staticidx, row in df.iterrows():
value= row['grain']

但这会返回所有行的值,包括具有 NaN 值的行。有没有办法从数据帧中删除 NaN 行或跳过数据帧中grain 等于 NaN 的行?

非常感谢

最佳答案

您可以在 dropna 中指定一个列列表,在其中对数据进行子集化:

subset : array-like Labels along other axis to consider, e.g. if you are dropping rows these would be a list of columns to include

>>> df.dropna(subset=['grain'])
id location grain
0 BBG.XETR.AD.S XETR 16.5450
1 BBG.XLON.VB.S XLON 6.2154
5 BBG.XLON.AN.S XLON 3.2150

关于python - 数据帧上的条件迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38984043/

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