【问题标题】:Pandas dataframe, check list in column an set value in different column熊猫数据框,列中的检查列表不同列中的设定值
【发布时间】:2023-01-18 02:36:23
【问题描述】:

我需要你的帮助来完成以下任务: 我有以下数据框:

test = {'Col1':[2,5],
        'Col2':[5,7],
        'Col_List':[['One','Two','Three','Four','Five'], ['Two', 'Four']],
       'One':[0,0],
       'Two':[0,0],
       'Three':[0,0],
       'Four':[0,0],
       'Five':[0,0],}

df=pd.DataFrame.from_dict(test)
df

看起来像:

Col1 Col2 Col_List One Two Three Four Five
2 5 [One, Two, Three, Four, Five] 0 0 0 0 0
5 7 [Two, Four] 0 0 0 0 0

我需要检查 Col_List 中的列表,并根据列表中的项目设置特定列中 Col1 列的值(OneTwoThreeFourFive)。

现在我想得到以下结果:

Col1 Col2 Col_List One Two Three Four Five
2 5 [One, Two, Three, Four, Five] 2 2 2 2 2
5 7 [Two, Four] 0 5 0 5 0

【问题讨论】:

    标签: python pandas list dataframe


    【解决方案1】:

    让我们尝试分解数据,拆开它,然后分配回去:

    s = (df[['Col1', 'Col_List']].explode('Col_List')
       .set_index('Col_List', append=True)['Col1']
       .unstack().fillna(df)
    )
    
    df.loc[s.index, s.columns] = s
    

    输出:

       Col1  Col2                       Col_List  One  Two  Three  Four  Five
    0     2     5  [One, Two, Three, Four, Five]  2.0  2.0    2.0   2.0   2.0
    1     5     7                    [Two, Four]  0.0  5.0    0.0   5.0   0.0
    

    【讨论】:

      猜你喜欢
      • 2018-08-03
      • 1970-01-01
      • 1970-01-01
      • 2018-07-10
      • 2022-01-01
      • 1970-01-01
      • 2017-08-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多