【问题标题】:How can I change a column value based on length of element in a DataFrame如何根据 DataFrame 中元素的长度更改列值
【发布时间】:2019-01-08 15:33:59
【问题描述】:

伙计们,

由于某些原因,我必须将 np.array 放入 DataFrame 的单列中。它看起来像:

A           B        C
1       [1,2]        0
2         [4]        0
3   [1,2,5,6]        0
7     [2,5,6]        0
4         [8]        0

是否有任何方法根据 B 列的长度设置 C 列而不对其进行迭代?例如。如果长度(col.B)== 2 或长度(col.B)== 4,C = 1,否则 C = -1。然后我期望:

A           B        C
1       [1,2]        1
2         [4]       -1
3   [1,2,5,6]        1
7     [2,5,6]        1
4         [8]       -1

非常感谢。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    lenisin 按条件使用numpy.where

    df['C'] = np.where(df['B'].str.len().isin({2,4}), 1, -1)
    
    print (df)
       A             B  C
    0  1        [1, 2]  1
    1  2           [4] -1
    2  3  [1, 2, 5, 6]  1
    3  7     [2, 5, 6] -1
    4  4           [8] -1
    

    【讨论】:

    • 完美使用str
    • @AntonvBR - 谢谢,为什么最好使用sets?为了获得更好的性能?
    • 是的,set 更快,比 list 更可取。
    • 其实我可能是错的......在这里看这个答案:stackoverflow.com/questions/50779617/…
    【解决方案2】:

    使用.apply:

    df['C']=df.apply(lambda row: 1 if len(row['B'].tolist()) in [2,4] else -1,axis=1)
    print(df)
    

    输出:

       A          B  C
    0  1      [1,2]  1
    1  2        [4] -1
    2  3  [1,2,5,6]  1
    3  7    [2,5,6] -1
    4  4        [8] -1
    

    (如果数据框元素是字符串,则执行ast.literal_eval

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-08-16
      • 2022-07-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-15
      • 1970-01-01
      • 2016-11-13
      相关资源
      最近更新 更多