【问题标题】:Replace list type column items by indices from other columns用其他列的索引替换列表类型的列项
【发布时间】:2021-06-02 23:07:50
【问题描述】:

我有一个这样的数据框,

df
col1     col2       col3             col4
 1       [1,2]    [0,0,0,0]      [0,0,0,0]
 0       [2,3]    [0,0,0,0]      [0,0,0,0]

现在我想根据 col1 和 col2 的索引将 col3、col4 列表项替换为 1。所以数据框应该是这样的,

col1     col2       col3             col4
 1       [1,2]    [0,1,0,0]      [0,1,1,0]
 0       [2,3]    [1,0,0,0]      [0,0,1,1]    

我正在尝试使用应用函数或自定义函数但没有得到想要的结果,正在寻找一些熊猫方法来有效地做到这一点。

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    在 pandas 中使用 list 效率不是很高,这是可能的解决方案:

    def f(x):
        x['col4'] = [1 if i in x['col2'] else 0 for i, y in enumerate(x['col4'])]
        x['col3'] = [1 if i ==  x['col1'] else 0 for i, y in enumerate(x['col3'])]
        return x
    
    df = df.apply(f, axis=1)
    print (df)
       col1    col2          col3          col4
    0     1  [1, 2]  [0, 1, 0, 0]  [0, 1, 1, 0]
    1     0  [2, 3]  [1, 0, 0, 0]  [0, 0, 1, 1]
    

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 1970-01-01
      • 2021-09-29
      • 1970-01-01
      • 2019-10-11
      • 1970-01-01
      • 1970-01-01
      • 2018-02-18
      • 1970-01-01
      相关资源
      最近更新 更多