2017-05-26 86 views
0

我有COLS一个DF如果其他条件熊猫

start end strand 
3 90290834 90290905 + 
3 90290834 90291149 + 
3 90291019 90291149 + 
3 90291239 90291381 + 
5 33977824 33984550 - 
5 33983577 33984550 - 
5 33984631 33986386 - 

什么,我想基础上,链列

f = pd.read_clipboard() 
f 
def addcolumns(row): 
    if row['strand'] == "+": 
     row["5ss"] == row["start"] 
     row["3ss"] == row["end"] 

    else: 
     row["5ss"] == row["end"] 
     row["3ss"] == row["start"] 
    return row 

f = f.apply(addcolumns, axis=1) 
KeyError: ('5ss', u'occurred at index 0') 

其中的一部分做的就是添加新列(5SS和3SS)代码错了?或者有更简单的方法来做到这一点?

回答

1

而不是使用.apply()的我建议使用np.where()代替:

df.loc[:, '5ss'] = np.where(f.strand == '+', f.start, f.end) 
df.loc[:, '3ss'] = np.where(f.strand == '+', f.end, f.start) 

np.where()基于三个参数

  • 逻辑条件创建一个新的对象(在这种情况下f.strand == '+'
  • 条件为真时的值
  • 当c ondition is false

使用apply()axis=1将函数应用于每列。所以即使你已经命名变量row,它实际上是遍历列。您可以省略axis参数或指定axis=0将函数应用于行。但考虑到你想要做什么,使用np.where()会更简单,它允许你为列分配指定一些条件逻辑。

+0

可以请你通过代码走过我们有趣的代码,它可以根据需要工作。 – sbradbio

+1

@sbradbio当然,加了一点解释。 – ASGM