2017-08-01 40 views
1

在下面的示例Pandas数据框中,Col2具有Col1中参数的值。例如,c的值在第1行中为2,在第2行中为7。是否有可能从Pandas的这个数据框中提取c的值?基于带有分隔符的依赖列解析值在Pandas中

pd.DataFrame({'col1': ['a:b:c:d', 'a:b:x:y:c:d'], 
      'col2': ['0:1:2:3', '3:4:5:6:7:8']}) 

预期输出:

pd.Series([2,7], name='c') 
+1

什么是预期的输出? – ksai

+0

@ kasi - 增加预期产出。谢谢! – JeeYem

回答

1

你可以做这样的事情:

def f(x): 
    p = dict(zip(x['col1'].split(":"),x['col2'].split(":"))) 
    return p['c'] 

df.apply(f,axis=1).astype(int).rename('c') 

或者,如果你想拉姆达:

df.apply(lambda x: dict(zip(x['col1'].split(":"),x['col2'].split(":")))['c'],axis=1).astype(int).rename('c') 

输出:

0 2 
1 7 
Name: c, dtype: int32