You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何移除字符串列表中的'nan'值?Python代码调试求助

解决方案

问题根源

你生成的列表元素是字符串拼接结果,当原DataFrame的Date或Time为缺失值(NaN)时,转成字符串后会变成'nan',最终得到类似'06/07/35 | nan'的元素。之前的方法失败是因为:

  • np.isnan和math.isnan仅能判断数值型NaN,无法识别字符串形式的'nan'
  • pd.isnull判断的是对象是否为缺失值,但你的元素是普通字符串,不是pandas的NaN对象,因此无法匹配

方法1:生成列表时直接过滤缺失行

在循环里先判断当前行的Date和Time是否都不为缺失值,再进行拼接和添加,从源头避免生成包含'nan'的元素:

import pandas as pd

test = []
for index, row in df.iterrows():
    # 检查Date和Time是否都不是缺失值
    if pd.notna(row['Date']) and pd.notna(row['Time']):
        x = str(row['Date']) + ' | ' + str(row['Time'])
        test.append(x)

print(test)

如果允许其中一个字段非空(比如只要Date或Time有一个存在就保留),可以把and改成or,根据需求调整。


方法2:对已生成的列表进行过滤

如果已经生成了包含'nan'的列表test,可以通过字符串匹配过滤掉包含'nan'的元素:

list_clean = [item for item in test if 'nan' not in item]
print(list_clean)

这种方法简单直接,适合已经有现成列表的场景。


优化版:不用循环,用pandas矢量化操作

pandas的矢量化操作比iterrows效率更高,尤其当DataFrame行数很多时:

import pandas as pd

# 先过滤掉Date或Time为缺失值的行
filtered_df = df[pd.notna(df['Date']) & pd.notna(df['Time'])]
# 拼接字符串
test = filtered_df['Date'].astype(str) + ' | ' + filtered_df['Time'].astype(str)
# 转成列表
test_list = test.tolist()

print(test_list)

这种方法避免了循环,代码更简洁高效。


内容的提问来源于stack exchange,提问作者Stacky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:36:34