【问题标题】:Pandas/Python: Replacing column values from another column values using .replace()Pandas/Python:使用 .replace() 从另一列值替换列值
【发布时间】:2021-03-31 23:15:19
【问题描述】:

数据:


import pandas as pd
dict= {'REF': ['A','B','C','D'],
        'ALT': [['E','F'], ['G'], ['H','I','J'], ['K,L']],
        'sample1': ['0', '0', '1', '2'],
        'sample2': ['1', '0', '3', '0']
        }
df = pd.DataFrame(dict)

问题: 我需要替换列“Sample1”和“Sample2”中的值。如果为 0,则应放置“REF”列值。如果为 1,则应放置“ALT”列中列表的第一个元素,如果为 2,则应放置“ALT”列列表中的第二个元素,依此类推。
我的解决方案:

 sample_list = ['sample1', 'sample2']
    for sample in sample_list:

        #replace 0s 
        df[sample] = df.apply(lambda x: x[sample].replace('0', x['REF']), axis=1)
        #replace other numbers
        for i in range(1,4):
            try:
                df[sample] = df.apply(lambda x: x[sample].replace(f'{i}', x['ALT'][i-1]), axis=1)
            except:
                pass

但是,由于每个'ALT'列行的列表长度不同,似乎存在IndexError,并且值在1之后没有被替换。您可以从输出中看到:

'{"REF":{"0":"A","1":"B","2":"C","3":"D"},"ALT":{"0":["E","F"],"1":["G"],"2":["H","I","J"],"3":["K"]},"sample1":{"0":"A","1":"B","2":"H","3":"2"},"sample2":{"0":"E","1":"B","2":"3","3":"D"}}'

我该如何解决?

更新: 如果我在 sample1 或 sample2 中有 NaN 值,我无法将值转换为 int 并且不知道如何跳过这些值

因此,NaN 值不应被转换并保持为 NaN

预期输出:

【问题讨论】:

  • 在示例 1 中,您有 2 个但列表中只有一个元素
  • 即使是2个元素还是不行
  • 我的问题是更多,在这些情况下应该怎么做?
  • 我认为你的 ALT 栏有错字,K 和 L 应该分开。

标签: python pandas list replace


【解决方案1】:

你可以这样做:

df['sample1'] = np.where(df['sample1'].eq(0), df['REF'],
                         [v[max(i - 1, 0)] for v, i in zip(df['ALT'], df['sample1'].astype(int))])

df['sample2'] = np.where(df['sample2'].eq(0), df['REF'],
                         [v[max(i - 1, 0)] for v, i in zip(df['ALT'], df['sample2'].astype(int))])

print(df)

输出

  REF        ALT sample1 sample2
0   A     [E, F]       E       E
1   B        [G]       G       G
2   C  [H, I, J]       H       J
3   D        [K]       K       K

请注意,鉴于您的示例中的输入无效,我使用了不同的输入。

【讨论】:

  • 谢谢!但是,如果示例列中的某些行中有 NaN 值,我该怎么办?那么 df['sample2'].astype(int)) 将不起作用。如何跳过这些行?
【解决方案2】:

使用 REF 和 ALT 列的简单连接并应用:

import pandas as pd
d= {'REF': ['A','B','C','D'],
        'ALT': [['E','F'], ['G'], ['H','I','J'], ['K','L']],
        'sample1': ['0', '0', '1', '2'],
        'sample2': ['1', '0', '3', '0']
        }
df = pd.DataFrame(d)


df["REF_ALT"] = df["REF"].map(list)+df["ALT"]  # concatenate REF and ALT
df["sample1"] = df.apply(lambda row: np.nan if np.isnan(row["sample1"]) else row["REF_ALT"][int(row["sample1"])], axis=1)
df["sample2"] = df.apply(lambda row: np.nan if np.isnan(row["sample2"]) else row["REF_ALT"][int(row["sample2"])], axis=1)
df.pop("REF_ALT")
df

【讨论】:

  • 感谢您的简单回答!但是,如果某些示例列中有 NaN 值,我该怎么办?然后 int(row["sample"]) 将不起作用
  • 在这种情况下,您需要预先将 NaN 值替换为 .fillna()
  • 但是我需要保留这些 NaN 值并且不要替换它们,所以我不能使用 .fillna() 或转换为整数
  • 好的,请说明在 nan 情况下的预期输出是什么
  • 预期输出只是在示例列中保留 NaN 值(不要替换),并且只替换数字
【解决方案3】:

一个简单的解决方案:

df = pd.DataFrame.from_dict({
 'REF': {0: 'A', 1: 'B', 2: 'C', 3: 'D'},
 'ALT': {0: ['E', 'F'], 1: ['G'], 2: ['H', 'I', 'J'], 3: ['K', 'L']},
 'sample1': {0: 0, 1: 0, 2: 1, 3: 2},
 'sample2': {0: 1, 1: 0, 2: 3, 3: 0},
})

# create a temp col s that includes a single string with letters:
df["s"] = df.REF + df.ALT.str.join("")    
df["sample1"] = df.apply(lambda x: x["s"][x.sample1], axis=1)
df["sample2"] = df.apply(lambda x: x["s"][x.sample2], axis=1)
df = df.drop(columns="s")

输出:

  REF        ALT sample1 sample2
0   A     [E, F]       A       E
1   B        [G]       B       B
2   C  [H, I, J]       H       J
3   D     [K, L]       L       D

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-24
    • 2019-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    • 1970-01-01
    • 2022-06-13
    相关资源
    最近更新 更多