【问题标题】:How to turn a cell of dataframe into list of list, when another cell does not equals to a certain value?当另一个单元格不等于某个值时,如何将数据帧的单元格转换为列表列表?
【发布时间】:2022-11-16 07:15:58
【问题描述】:

我有以下熊猫数据框

Consideration_level    |  Consideration_value
-------------------------------------------------
Car_ID                        00111
Car_ID                        00222
Car_type, Location            Jeep, NYC
Car_Color, Location           Pink, BOS

我想把它变成

Consideration_level    |  Consideration_value
-------------------------------------------------
Car_ID                        [00111]
Car_ID                        [00222]
Car_type, Location            [[Jeep], [NYC]]
Car_Color, Location           [[Pink], [BOS]]

所以本质上,我希望当 Consideration_level 不等于“Car_ID”时,Consideration_value 应该是一个列表列表;当 Consideration_level 等于“Car_ID”时,Consideration_value 将是一个列表。

我试过了

列表到列表的列表中

def 提取数字(lst): 返回 [[el] for el in lst]

但我不知道如何在这里做逻辑......感谢任何帮助!

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    尝试:

    df["Consideration_value"] = df["Consideration_value"].apply(
        lambda x: [v for v in map(str.strip, x.split(","))]
    )
    
    mask = ~df["Consideration_level"].eq("Car_ID")
    df.loc[mask, "Consideration_value"] = df.loc[mask, "Consideration_value"].apply(
        lambda x: [[l] for l in x]
    )
    
    print(df)
    

    印刷:

       Consideration_level Consideration_value
    0               Car_ID             [00111]
    1               Car_ID             [00222]
    2   Car_type, Location     [[Jeep], [NYC]]
    3  Car_Color, Location     [[Pink], [BOS]]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多