【发布时间】:2019-12-15 21:07:41
【问题描述】:
我正在尝试将函数 convert_label() 应用于我的数据框的 CR_df['label'] 列。函数的输出存储在单独的列 CR_df['y'] 中。但是,我的 CR_df['label'] 列包含具有 NaN 值的单元格。我只想将我的函数应用于 CR_df['label'] 中没有 NaN 值的单元格。如果单元格确实有 NaN 值,我想在相应的 CR_df['y'] 单元格中返回 NaN。
我不想检查我是否有 NaN 值,如果是 NaN,我需要返回 NaN。
我的(容易出错的)解决方案尝试
def convert_label(label):
if "pos" in label:
output = 1.0
elif "neg" in label:
output = 0.0
else:
output = label
return output
我尝试将 NaN 转换为字符串,然后应用我的函数,但现在我需要将 CR_df['y'] 中的所有字符串“nan”更改为实际的 NaN 或 null 值
CR_df['y'] = CR_df['label'].astype(str).apply(convert_label)
我附上了我的输出图片
另外,这是我的数据框的代码
CR_train_file='data/custrev_train.tsv'
CR_test_file = 'data/custrev_test.tsv'
CR_train_df = pd.read_csv(CR_train_file, sep='\t', header=None)
CR_train_df.columns = ['index', 'label', 'review']
CR_test_df = pd.read_csv(CR_test_file, sep='\t', header=None)
CR_test_df.columns = ['index', 'review']
CR_test_df
CR_df = pd.concat([CR_train_df,CR_test_df], axis=0, ignore_index=True)
【问题讨论】:
-
这能回答你的问题吗? How can I check for NaN values?
-
不,它没有。我的问题是如何返回 NaN 值
-
您可以为您的数据框添加一个示例吗?
-
上面提供了数据框示例
-
下次可以发布代码来生成这样的数据帧,而不是图片。