使用条件将列表的pandas列拆分为多个列。

时间:2018-06-25 10:24:47

标签: python pandas

我有一个带有两列的pandas dataFrame,如下所示:

from multiprocessing import cpu_count

我需要使用熊猫将列表的这些列分成名为1st_half_T1、2nd_half_T1、1st_half_T2和2nd_half_T2的4列。条件是,如果d1 = {'Time1': [[93, 109, 187],[159],[94, 96, 154, 169]], 'Time2':[[16, 48, 66, 128],[123, 136],[40,177,192]]} df = pd.DataFrame(d1) ,Time1分为1st_half,如果Time <= 96,Time2分为2nd_half,并将相同的条件应用于Time > 96会给出以下输出。

Time2

3 个答案:

答案 0 :(得分: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]

答案 1 :(得分:2)

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]

答案 2 :(得分:1)

fun Client.executeCustom(onResponse: (Response) -> Unit, onError: (Error) -> Unit) { execute(object : Callback() { override fun onResponse(response: Response) = onResponse(response) override fun onError(error: Error) = onError(error) }) } 与自定义功能一起使用

apply