Skip to main content
 首页 » 编程设计

python之在python中使用pandas根据其他列中给定的值选择列

2025年05月04日13lyhabc

我有一个数据框:

a   b   c   d...... 
 
1   1 
3   3   3   5 
4   1   1   4   6 
1   0 

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

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 

请您参考如下方法:

为此定义一个小函数:

def select(df, r): 
    return df.iloc[r, 1:1 + df.iat[r, 0]]   

该函数使用 iat 查询该行的 a 列,并使用 iloc 从同一行中选择列。

这样调用它:

select(df, 0) 
 
b    1.0 
Name: 0, dtype: float64 

还有,

select(df, 1) 
 
b    3.0 
c    3.0 
d    5.0 
Name: 1, dtype: float64 

根据您的编辑,考虑这个 -

df 
 
   a  b  c  d  e 
0  1  1  0  0  0 
1  3  3  3  5  0 
2  4  1  1  4  6 
3  1  0  0  0  0 

在此处使用where/mask(使用numpy广播)+ agg -

df['e'] = df.iloc[:, 1:]\ 
            .astype(str)\ 
            .where(np.arange(df.shape[1] - 1) < df.a[:, None], '')\ 
            .agg(''.join, axis=1) 
 
df 
 
   a  b  c  d     e 
0  1  1  0  0     1 
1  3  3  3  5   335 
2  4  1  1  4  1146 
3  1  0  0  0     0 

如果没有匹配项,则 e 中的那些条目将为空字符串。只需使用 replace -

df['e'] = df['e'].replace('', np.nan)