在python中使用pandas根据其他列中给出的值选择列 [英] Selecting columns based on value given in other column using pandas in python

查看:54
本文介绍了在python中使用pandas根据其他列中给出的值选择列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据框:

a   b   c   d......

1   1
3   3   3   5
4   1   1   4   6
1   0

我想根据列a"中给出的值选择列数.在这种情况下,对于第一行,它只会选择列 b.我怎样才能实现这样的目标:

I want to select number of columns based on value given in column "a". In this case for first row it would only select column b. How can I achieve something like:

df.iloc[:,column b:number of columns corresponding to value in column a]

我的预期输出是:

a   b   c   d   e
1   1   0   0   1     # 'e' contains value in column b because colmn a = 1 
3   3   3   5   335   #  'e' contains values of column b,c,d because colm a 
4   1   1   4   1      #  = 3
1   0           NAN

推荐答案

numpy 切片方法

a = v[:, 0]
b = v[:, 1:]
n, m = b.shape
b = b.ravel()
b = np.where(b == 0, '', b.astype(str))
r = np.arange(n) * m
f = lambda t: b[t[0]:t[1]]

df.assign(g=list(map(''.join, map(f, zip(r, r + a)))))

   a  b  c  d  e     g
0  1  1  0  0  0     1
1  3  3  3  5  0   335
2  4  1  1  4  6  1146
3  1  0  0  0  0      

这篇关于在python中使用pandas根据其他列中给出的值选择列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆