Skip to main content
 首页 » 编程设计

python之列切片 Pandas

2025年05月04日19dflying

这是虚拟的 DataFrame:

d = {'col_1': [1, 2], 'col_n_1': [3, 4], 'col_2': [2, 1], 'col_n_2': [6, 3]} 
df = pd.DataFrame(data=d) 
 
 
   col_1    col_2   col_n_1   col_n_2 
0      1        2         3         6 
1      2        1         4         3 
2      1        1         4         5 

我正在寻找一种很好的方法来从 col_n_1 中提取值,其中 col_1 == 1 和 col_n_2 中 col_2 = = 1 在一个看起来像这样的新列中:

new_col 
      3 
      3 
    4,5 

请您参考如下方法:

使用where通过掩码获取值,然后将 join 列放在一起:

L = ['col_1','col_2'] 
L1 = ['col_n_1','col_n_2'] 
df['new'] = (df[L1].astype(str).where(df[L].eq(1).values, axis=1) 
                  .apply(lambda x: ','.join(x.dropna()), 1)) 

如果只有 2 列的解决方案:

L = ['col_1','col_2'] 
L1 = ['col_n_1','col_n_2'] 
df1 = df[L1].astype(str).where(df[L].eq(1).values, axis=1) 
df['new'] = (df1['col_n_1'] .fillna('') + ',' + df1['col_n_2'] .fillna('')).str.strip(',') 

或者添加 , 然后 sum 的解决方案,最后删除尾随 ,:

df['new'] = (df[L1].astype(str).where(df[L].eq(1).values) 
                  .add(', ') 
                  .fillna('') 
                  .sum(axis=1) 
                  .str.strip(', ')) 

print (df) 
   col_1  col_2  col_n_1  col_n_2  new 
0      1      2        3        6    3 
1      2      1        4        3    3 
2      1      1        4        5  4,5