【问题标题】:Using condition to split pandas column of lists into multiple columns.使用条件将列表的 pandas 列拆分为多列。
【发布时间】:2018-06-25 10:24:47
【问题描述】:

我有一个带有两列的 pandas 数据框,如下所示:

d1 = {'Time1': [[93, 109, 187],[159],[94, 96, 154, 169]],
              'Time2':[[16, 48, 66, 128],[123, 136],[40,177,192]]}

df = pd.DataFrame(d1)

我需要使用 pandas 将这些列表列拆分为 4 列,分别命名为 1st_half_T1、2nd_half_T1、1st_half_T2 和 2nd_half_T2。条件是,如果 Time <= 96 和 2nd_half 如果 Time > 96 和应用相同的条件 Time2,则 Time1 拆分为 1st_half 会得到以下输出。

  1st_half_T1           2nd_half_T1     1st_half_T2      2nd_half_T2
0       [93]             [109, 187]    [16, 48, 66]           [128]
1         []                  [159]              []      [123, 126]
2   [94, 96]             [154, 169]            [40]      [177, 192]

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    apply 与自定义函数一起使用

    def my_split(row):
        return pd.Series({
            '1st_half_T1': [i for i in row.Time1 if i <= 96],
            '2nd_half_T1': [i for i in row.Time1 if i > 96],
            '1st_half_T2': [i for i in row.Time2 if i <= 96],
            '2nd_half_T2': [i for i in row.Time2 if i > 96]
        })
    df.apply(my_split, axis=1)
    
    Out[]:
      1st_half_T1   1st_half_T2 2nd_half_T1 2nd_half_T2
    0        [93]  [16, 48, 66]  [109, 187]       [128]
    1          []            []       [159]  [123, 136]
    2    [94, 96]          [40]  [154, 169]  [177, 192]
    

    【讨论】:

    • 谢谢大家的帮助。
    【解决方案2】:

    将列表推导与DataFrame 构造函数一起使用:

    t11 = [[y for y in x if y <=96] for x in df['Time1']]
    t12 = [[y for y in x if y >96] for x in df['Time1']]
    
    t21 = [[y for y in x if y <=96] for x in df['Time2']]
    t22 = [[y for y in x if y >96] for x in df['Time2']]
    
    df = pd.DataFrame({'1st_half_T1':t11, '2nd_half_T1':t12,'1st_half_T2':t21, '2nd_half_T2':t22})
    print (df)
      1st_half_T1 2nd_half_T1   1st_half_T2 2nd_half_T2
    0        [93]  [109, 187]  [16, 48, 66]       [128]
    1          []       [159]            []  [123, 136]
    2    [94, 96]  [154, 169]          [40]  [177, 192]
    

    【讨论】:

      【解决方案3】:
      df_new = pd.DataFrame()
      
      df_new.loc[:,'1st_half_T1'] = df['Time1'].apply(lambda x : [y for y in x if y <=96])
      df_new.loc[:,'2nd_half_T1'] = df['Time1'].apply(lambda x : [y for y in x if y >96])
      df_new.loc[:,'1st_half_T2'] = df['Time2'].apply(lambda x : [y for y in x if y <=96])
      df_new.loc[:,'2nd_half_T2'] = df['Time2'].apply(lambda x : [y for y in x if y >96])
      df_new
      Out[64]: 
        1st_half_T1 2nd_half_T1   1st_half_T2 2nd_half_T2
      0        [93]  [109, 187]  [16, 48, 66]       [128]
      1          []       [159]            []  [123, 136]
      2    [94, 96]  [154, 169]          [40]  [177, 192]
      

      【讨论】:

        猜你喜欢
        • 2023-01-11
        • 2016-05-31
        • 2020-02-10
        • 2021-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多