【问题标题】:Assign value to a column based on the length of a list in another column根据另一列中列表的长度为列赋值
【发布时间】:2021-08-27 20:17:38
【问题描述】:
Col1 Col2 ListOfQs
First Third ['abc', 'def', 'ghi']
Second Fourth ['row', 'col']

如果 df['ListOfQs'] 中的列表长度 > 2,我想在 DataFrame 中创建一个新列,该列包含 Col2 中的值,如果不是,则包含 Col1 中的值。

我可以通过以下方式获取列表的长度:

df['lenList'] = df['ListOfQs'].str.len()

但是 df['lenList'] 的类型是一个系列,它不会让我把它当作一个数字来对待。

我试过了:

df['lenList'] = pd.to_numeric(df['lenList'])

type(df['lenList']) 仍然是一个系列。

如果我得到它是数字,我可以在 for 循环中使用它。我在想有人可能知道如何使用 lambda 一步完成。我会尽我所能提供帮助。

【问题讨论】:

    标签: python list dataframe lambda


    【解决方案1】:

    你可以使用np.where:

    df["new_col"] = np.where(df["ListOfQs"].str.len() > 2, df["Col2"], df["Col1"])
    print(df)
    

    打印:

         Col1    Col2         ListOfQs new_col
    0   First   Third  [abc, def, ghi]   Third
    1  Second  Fourth       [row, col]  Second
    

    如果需要将ListOfQs转换为list,可以先申请ast.literal_eval

    from ast import literal_eval
    
    df["ListOfQs"] = df["ListOfQs"].apply(literal_eval)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-19
      • 2021-11-29
      • 1970-01-01
      • 2019-11-28
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      • 2020-10-11
      相关资源
      最近更新 更多