繁体   English   中英

列切片熊猫

[英]Column slice pandas

这是虚拟的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 == 1col_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

从耶兹借用名单

df[L].eq(1).rename(columns=dict(zip(L,L1))).mul((df[L1].astype(str)+',')).sum(1).str[:-1]
Out[126]: 
0      3
1      3
2    4,5
dtype: object

这可以通过apply()方法和lambda函数来完成。 apply() index参数设置为1 apply()将在数据帧的每一行上调用给定函数。 因此,唯一的麻烦是编写该函数-我认为最好的解决方案是创建一个包含该行的col_n_1col_n_2或两者都不包含的列表,然后用逗号将列表连接起来。 像这样:

df['new'] = df.apply(lambda row: ','.join([str(row.col_n_1)] if row.col_1 == 1 else [] + [str(row.col_n_2)] if row.col_2 == 1 else []), axis = 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM