Skip to main content
 首页 » 编程设计

python之在 Pandas 数据框中使用条件值时出错

2025年01月19日10java哥

我正在尝试使用以下代码将新列 wdf['Thunder'] 设置为 wdf['RngT] 的值,如果单词 Thunderstorm 位于 wdf['Notes'] 列中。但是,我不断收到错误 TypeError: argument of type 'float' is not iterable。没有一列是 float 。 RngT 是一个int,Notes 是一个对象。完整代码为:

wdf['Thunder'] = [wdf['RngT'] if 'Thunderstorm' in x else 0 for x in wdf['Notes']] 

pandas 的新手,如有任何见解,我们将不胜感激。

谢谢!

请您参考如下方法:

您可以考虑一个高性能的替代方案,np.where:

wdf['Thunder'] = np.where( 
    wdf['Notes'].astype(str).str.contains('Thunderstorm'), wdf['RngT'], 0 
) 

请注意,您的第一种方法可能行不通,因为您的专栏混合了字符串和 float 。在检查包含之前使用 astype(str) 应该可以解决这个问题。