You need to enable JavaScript to run this app. DataFrame逐行将重复值替换为1单次值替换为0的实现方法
优惠活动
大模型
产品
解决方案
定价
更多

DataFrame逐行将重复值替换为1单次值替换为0的实现方法

实现代码(基于Pandas)

首先导入依赖库:

import pandas as pd
import numpy as np

先构造你提供的示例DataFrame:

df = pd.DataFrame({
    'genome': ['genome_1', 'genome_2', 'genome_3', 'genome_4', 'genome_5'],
    'time_1': [28, 2, 12, 2, 3],
    'time_2': [28, 4, 12, np.nan, 3],
    'time_3': [np.nan, 5, 12, np.nan, np.nan],
    'time_4': [np.nan, 2, 12, np.nan, np.nan]
})

核心处理逻辑:

def row_transform(row):
    # 统计当前行所有非空值的出现频次
    freq = row.value_counts(dropna=True)
    # 逐个元素替换
    return row.map(lambda x: 1 if pd.notna(x) and freq[x] >=2 else (0 if pd.notna(x) else x))

# 仅对时间列按行执行转换,保留genome列不变
df.iloc[:, 1:] = df.iloc[:, 1:].apply(row_transform, axis=1)

执行后df就是你需要的结果。

逻辑说明

  1. 用apply(axis=1)指定按行遍历时间列的数值
  2. 对每一行先统计所有非NA值的出现次数,排除空值干扰
  3. 元素级判断:非NA值出现≥2次替换为1,仅出现1次替换为0,原有NA值直接保留

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 12:45:04